Enumerable::group_by extension
Friday, August 3rd, 2007I was working recently on a simple RoR website and needed an easy way to display columns of data on the front page. The easiest possible query was a simple find(:all) but after that I wanted to divide the items returned into groups that would be rendered separately. I wasn’t aware of any grouping available in enumerable so I did a bit of a search and ran across this discussion thread. I didn’t read the entire thread (and it’s mention of Set::classify which I was not aware of) but liked the group_by extension it proposed.
module EnumerableExtension
def group_by(store=Hash.new)
self.each do |elem|
group = yield elem
(store[group] ||= []) << elem
end
store
end
end
Enumerable.send(:include, EnumerableExtension)
controller
@collections = Collection.find(:all).group_by do |collection|
collection.name.to_sym
end
@left = collections[:left]
@right = collection[:right]
view
<%= render :partial => “left_well”, :locals => {:items => @left} %>
<%= render :partial => “right_well”, :locals => {:items => @right} %>
If I had to do this again I probably would have used Set::classify but I still like the group_by available in Enumerable and I like not being forced to create a set simply to group objects.