ruby-on-rails - 按天对 Mongoid 对象进行分组

标签 ruby-on-rails ruby mongoid grouping

在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似 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/

相关文章:

ruby-on-rails - Rails rake 数据库 :migrate aborts with generated model

ruby-on-rails - 我可以使用 Nokogiri 插入原始 XML 字符串吗?

ruby-on-rails - 为什么 Rails 2.3 不生成 Gemfile?

ruby-on-rails - rails 功能测试中的身份验证问题

ruby-on-rails - 带有验证助手的自定义验证器

ruby-on-rails - 如何在依赖 gem 中添加调试器(binding.pry)?

Ruby:邮件 gem 在邮件中的 60 个字符后添加\r\n

ruby-on-rails - 在生产中使用 MongoDB 构建索引的时间和频率

model-view-controller - 在 Rails 3 中添加按钮点击计数器

ruby-on-rails - ruby rails : Cucumber: how do I test if a link opens in a new window/tab?