-3

我从下面这样的代码中得到哈希

{"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}}
  …
]
4

2 回答 2

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}}
# ]
于 2017-04-24T15:35:53.300 回答
2

假设所有月份的数据都在那里:

input.each_slice(3)
     .map
     .with_index(1) { |a, i| { name: "Q#{i}", data: a.to_h } }
于 2017-04-24T16:05:06.243 回答