ruby-on-rails – 按天分组Mongoid对象
发布时间:2020-12-17 03:34:38 所属栏目:百科 来源:网络整理
导读:在控制台中玩了很多次之后,我想出了这种方法,可以在它们发生的那一天将类似activerecord的(Mongoid)对象分组.我不确定这是实现这一目标的最佳方式,但它确实有效.有没有人有更好的建议,或者这是一个好方法吗? #events is an array of activerecord-like obje
在控制台中玩了很多次之后,我想出了这种方法,可以在它们发生的那一天将类似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使用#group_by方法可以这样工作: events.group_by { |event| event.time.day } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |