SpicyCode

The ramblings of Chad Humphries

Revisiting enumerable

I was back in an old project reviewing some code and I noticed an area where the activesupport methods in_groups_of and group_by could really help. In case anyone hasn’t seen them they work as follows.

Enumerable#group_by is for collecting an enumerable into sets, grouped by the result of a block. Useful, for example, for grouping records by date.

latest_transcripts.group_by(&:day).each do |day, transcripts| 
  p "#{day} -> #{transcripts.map(&:class) * ', '}" 
end

The above gives you the following results (as an example).

"2006-03-01 -> Transcript" 
"2006-02-28 -> Transcript" 
"2006-02-27 -> Transcript, Transcript" 
"2006-02-26 -> Transcript, Transcript" 

Array#in_groups_of let’s you iterate over an array in groups of a certain size, optionally padding any remaining slots with a specified value (nil by default).

%w(1 2 3 4 5 6 7).in_groups_of(3) {|g| p g}

Would give you:

["1", "2", "3"]
["4", "5", "6"]
["7", nil, nil]
Advertisements

Written by spicycode

December 24, 2006 at 6:31 pm

Posted in programming

Tagged with ,

%d bloggers like this: