按天分组Mongoid对象

5

在控制台上进行了很多尝试后,我想出了一种方法来按发生日期对类似于 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],
      ...
    }

谢谢!


1
你的问题中提到了MongoDB / MongoId,但是你又提到了ActiveRecord。请问一下你是在使用MongoId还是ActiveRecord呢? - Simone Carletti
对,我的意思是说ActiveRecord类似的对象,因为Mongoid与ActiveRecord的API非常相似。已编辑。 - Adam
1个回答

8

经过深思熟虑并得到Forrst的帮助后,我得出了以下结论:

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

显然,Rails使用#group_by方法为Enumerable打补丁,其工作方式如下:
events.group_by { |event| event.time.day }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接