本文介绍了按天对Mongoid对象进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在控制台中进行了大量的操作之后,我想出了一种方法,可以将类似于activerecord的对象(Mongoid)按发生的日期进行分组.我不确定这是否是实现此目标的最佳方法,但它确实有效.有没有人有更好的建议,或者这是一个好方法吗?

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],
      ...
    }

谢谢!

推荐答案

经过进一步的思考和Forrst的一些帮助,我想到了:

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

显然,Rails的monkeypatches可通过这样的#group_by方法枚举:

Apparently Rails monkeypatches Enumerable with a #group_by method that works like this:

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

这篇关于按天对Mongoid对象进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 03:29