From: Todd Benson Date: 2008-03-01T18:03:46+09:00 Subject: Re: making a monthly calendar... On Sat, Mar 1, 2008 at 2:34 AM, Mikkel Bruun wrote: > Todd Benson wrote: > > On Fri, Feb 29, 2008 at 4:30 PM, Mikkel Bruun > > wrote: > > >> 5. week i need to show march 1 and 2 and the same in the front... > >> > > >> mikkel > > > > Here's one for fun. I'm pretty sure you don't want to use this (for > > all I know, you might be laughed out of the room :), but it > > demonstrates some methods... > > > woot, it actually works.... > > ive been doing ruby since 2000 but i cant undestand what the h*ll going > on there.... > > can you give me a walkthrough or a more humane rewrite ;-) Okay, changing the code... require 'enumerator' # I need that for the each_slice method later today = Date.today offset = today.wday # gives me the day of the week months_of_concern = (-1..1).inject([]) {|arr, i| arr << (today.month + i)} # just running through -1 to 1 and adding to the current month # it gives you last month, current month, and next month numbers # which will be handed to months_of_concern after the block finishes month_ranges = months_of_concern.map {|month| 1..Date.new( today.year, month, -1 ).day} # building ranges to later turn into arrays # you get previous, current, and future month ranges # the month days # -1 is used, as Morton so excellently pointed out # as the _last_ number # this is common in Ruby day_sets = month_ranges.map {|i| i.to_a} # turning the Range objects (3 of them) into Array objects # I should have used {|i| i.map} here because it # would have been cuter, which is mostly disapproved # of in production code :) offset.times { day_sets[1].unshift day_sets[0].pop } # Here, we're just moving the last numbers of the last # month to the first part of this month one by one day_sets[1..2].flatten.slice(0..35).compact.each_slice(7) {|i| p i} # This one is actually easy to understand. # Grab what we now have as the current month, # tap on the ending month, # flatten it (turn it into one big array), # slice off the numbers that are in slots 0 to 35 # compact (there might be nils) # each_slice simply builds arrays by # grabbing things 7 at a time. Keep in mind scope. The "i" variable is local to each block; all by himself. It doesn't have to be "i", also. Todd