Todd Benson
3/3/2008 1:20:00 AM
Oh my goodness! A thousand apologies. I gave you a rotating month. See below.
On Sat, Mar 1, 2008 at 3:03 AM, Todd Benson <caduceass@gmail.com> wrote:
>
> On Sat, Mar 1, 2008 at 2:34 AM, Mikkel Bruun <mikkel@helenius.dk> wrote:
> > Todd Benson wrote:
> > > On Fri, Feb 29, 2008 at 4:30 PM, Mikkel Bruun <mikkel@helenius.dk>
> > > 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...
>
> <CODE>
>
> require 'enumerator'
> # I need that for the each_slice method later
> today = Date.today
offset = Date.new(today.year, today.month, 1).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.
>
> </CODE>
>
> Keep in mind scope. The "i" variable is local to each block; all by
> himself. It doesn't have to be "i", also.
My original code only worked when run on the first of the month.
Pretty funny, actually. It's one of those things that a unit test
wouldn't catch unless the test was written correctly.
Todd