开发者

Grouping Mongoid Objects by Day

After much playing around in the console, I came up with this method to group activerecord-like (Mongoid) objects by the day on which they occured. I'm not sure this is the best way to accomplish this, but it works. Does anyone have a better suggestion, or is this a good way to do it?

#events is an ar开发者_开发知识库ray 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!


After more thought and some help from Forrst, I came up with this:

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

Apparently Rails monkeypatches Enumerable with a #group_by method that works like this:

events.group_by { |event| event.time.day }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜