Grouping Mongoid by Day objects

After you played a lot in the console, I came up with this method to group activerecord-like (Mongoid) objects by the time they happened. I'm not sure if this is the best way to achieve this, but it works. Does anyone have a better suggestion, or is this a good way to do this?

#events is an array of activerecord-like objects that include a time attribute events.map{ |event| # convert events array into an array of hashes with the day of the month and the event { :number => event.time.day, :event => event } }.reduce({}){ |memo,day| # convert this into a hash with arrays of events keyed by their day or occurrance ( memo[day[:number]] ||= [] ) << day[:event] memo } => { 29 => [e1, e2], 28 => [e3, e4, e5], 27 => [e6, e7], ... } 

Thanks!

+5
source share
1 answer

After much thought and some help from Forrst, I came up with the following:

 events.inject({}) do |memo,event| ( memo[event.time.day] ||= [] ) << event memo end 

Apparently Rally monkeypatches Listed using the #group_by method, which works as follows:

 events.group_by { |event| event.time.day } 
+8
source

All Articles