我有来自下面的代码的哈希
{"Jan 2016"=>4649, "Feb 2016"=>3945, "Mar 2016"=>4870, "Apr 2016"=>4872,
"May 2016"=>6494, "Jun 2016"=>4981, "Jul 2016"=>9949, "Aug 2016"=>4842,
"Sep 2016"=>5820, "Oct 2016"=>4934, "Nov 2016"=>4136, "Dec 2016"=>8856,
"Jan 2017"=>3762, "Feb 2017"=>3261, "Mar 2017"=>2185, "Apr 2017"=>702}
从代码
生成的这个哈希@bookings.group_by_month(:check_in_date, format: "%b %Y").sum(:total_night)
我使用此代码生成带有chartkick的图表,我想按季度分组以生成数据系列,以便我可以为每个系列添加不同的颜色,
预期输出
[
{name: "Q1",data: {"Jan 2016"=>4649, "Feb 2016"=>3945, "Mar 2016"=>4870}},
{name: "Q2",data: {"Apr 2016"=>4872, "May 2016"=>6494, "Jun 2016"=>4981}}
…
]
答案 0 :(得分:4)
a.group_by { |k, v| [Date.parse(k).year, ((Date.parse(k).month - 1) / 3) + 1] }
.map { |k, v| { quarter: k, data: v.to_h} }
# [
# {:quarter=>[2016, 1], :data=>{"Jan 2016"=>4649, "Feb 2016"=>3945, "Mar 2016"=>4870}},
# {:quarter=>[2016, 2], :data=>{"Apr 2016"=>4872, "May 2016"=>6494, "Jun 2016"=>4981}},
# {:quarter=>[2016, 3], :data=>{"Jul 2016"=>9949, "Aug 2016"=>4842, "Sep 2016"=>5820}},
# {:quarter=>[2016, 4], :data=>{"Oct 2016"=>4934, "Nov 2016"=>4136, "Dec 2016"=>8856}},
# {:quarter=>[2017, 1], :data=>{"Jan 2017"=>3762, "Feb 2017"=>3261, "Mar 2017"=>2185}},
# {:quarter=>[2017, 2], :data=>{"Apr 2017"=>702}}
# ]
答案 1 :(得分:2)
假设所有月份的数据都在那里:
input.each_slice(3)
.map
.with_index(1) { |a, i| { name: "Q#{i}", data: a.to_h } }