在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似 activerecord 的 (Mongoid) 对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?
#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],
...
}
谢谢!
最佳答案
经过更多思考和 Forrst 的一些帮助,我想到了这个:
events.inject({}) do |memo,event|
( memo[event.time.day] ||= [] ) << event
memo
end
显然,Rails monkeypatches Enumerable 使用 #group_by 方法,其工作方式如下:
events.group_by { |event| event.time.day }
关于ruby-on-rails - 按天对 Mongoid 对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5482227/