【问题标题】:Grouping Mongoid Objects by Day按天分组 Mongoid 对象
【发布时间】:2011-03-30 05:27:09
【问题描述】:

在控制台中玩了很多之后,我想出了这个方法来按它们发生的日期对类似 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],
      ...
    }

谢谢!

【问题讨论】:

  • 您的问题是 MongoDB/MongoId,但您提到了 ActiveRecord。您能否澄清一下您使用的是 MongoId 还是 ActiveRecord?
  • 对,我的意思是说类似于 ActiveRecord 的对象,因为 Mongoid 非常接近 ActiveRecord 的 API。已编辑。

标签: ruby-on-rails ruby mongoid grouping


【解决方案1】:

经过更多的思考和 Forrst 的帮助,我想出了这个:

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

显然 Rails 的 monkeypatches 可通过 #group_by 方法枚举,其工作方式如下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多