[# [[Sat, 01 Jan 2011 18:14:08 UTC +00:00-6ren">
gpt4 book ai didi

ruby-on-rails - 如何按天而不是日期分组?

转载 作者:数据小太阳 更新时间:2023-10-29 06:32:41 25 4
gpt4 key购买 nike

好的,我有

 >> list = Request.find_all_by_artist("someBand")
=> [#<Request id: 1, artist: "someBand", song: "someSong", venue: "Knebworth - Stevenage, United Kingdom", showdate: "2011-07-01", amount: nil, user_id: 2, created_at: "2011-01-01 18:14:08", updated_at: "2011-01-01 18:14:09".............

然后

list.group_by(&:created_at).map {|k,v| [k, v.length]}.sort
=> [[Sat, 01 Jan 2011 18:14:08 UTC +00:00, 10], [Sun, 09 Jan 2011 18:34:19 UTC +00:00, 1], [Sun, 09 Jan 2011 18:38:48 UTC +00:00, 1], [Sun, 09 Jan 2011 18:51:10 UTC +00:00, 1], [Sun, 09 Jan 2011 18:52:30 UTC +00:00, 1], [Thu, 10 Feb 2011 02:22:08 UTC +00:00, 1], [Thu, 10 Feb 2011 20:02:20 UTC +00:00, 1]]

问题是我有几个星期日,1 月 9 日和 10 日的一对,而不是像这样的

这就是我想要的

=> [[Sat, 01 Jan 2011 18:14:08 UTC +00:00, 10], [Sun, 09 Jan 2011 18:34:19 UTC +00:00, 4], [Thu, 10 Feb 2011 20:02:20 UTC +00:00, 2]]

最佳答案

我认为这是一个更加优雅和简单的解决方案

list.group_by{|x| x.created_at.strftime("%Y-%m-%d")} 

关于ruby-on-rails - 如何按天而不是日期分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4987392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com