7.24. Dividing a Month into Weeks

Imagine that you wanted to divide a month into weeks—for example, to print a calendar. The following code does that. The array returned is made up of subarrays, each of size seven (7); Sunday corresponds to the first element of each inner array. Leading entries for the first week and trailing entries for the last week may be nil.

def calendar(month,year) days = month_days(month,year) t = Time.mktime(year,month,1) first = t.wday list = *1..days weeks = [[]] week1 = 7 - first week1.times { weeks[0] << list.shift } nweeks = list.size/7 + 1 nweeks.times do |i| weeks[i+1] ||= [] 7.times do break if list.empty? weeks[i+1] << list.shift end end pad_first = 7-weeks[0].size pad_first.times { weeks[0].unshift(nil) } pad_last ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.