October 2006
Intermediate to advanced
888 pages
16h 55m
English
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 ...Read now
Unlock full access