Grouping Mongoid Objects by Day

青春壹個敷衍的年華 提交于 2019-12-22 07:11:08

问题


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 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!


回答1:


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 }


来源:https://stackoverflow.com/questions/5482227/grouping-mongoid-objects-by-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!