我希望日期范围为1.month.ago..Date.today
,然后每天选择最高温度(因此应获得30个单独的数字),然后总结结果。
我以JSON格式获取数据,结构如下
{"status": "ok", "data": [{"temperature": 22.4, "date": "20160815-0345"}}
我通过循环解析数据。
@data['data'].each do |d|
maxTotal << [DateTime.parse(d['date']), d['temperature']]
end
但没有说明如何选择每天的最大值然后总结。
@total = maxTotal { |a| a[0].to_date == (1.month.ago.to_date) }.max { |a,b| a[1] <=> b[1] }.sum[1]
答案 0 :(得分:1)
json_data = @data['data']
sum_of_max_temperature_in_each_day = json_data.
group_by{ |h| Date.parse(h[:date]) }.
reject{ |k, v| !( ((30.days.ago.to_date)..(Date.today)) === k ) }.
inject(0){ |sum, h| sum + h.second.max_by{ |h| h[:temperature] }[:temperature] }
# Example; let json_data be
json_data = [
{"temperature": 22.4, "date": "20160815-0345"},
{"temperature": 10.4, "date": "20160815-1435"},
{"temperature": 15.8, "date": "20990101-0430"},
{"temperature": 4, "date": "20160816-0101"}
]
# sum of max temperature each day within last 30 days
puts json_data.
group_by{ |h| Date.parse(h[:date]) }.
reject{ |k, v| !( ((30.days.ago.to_date)..(Date.today)) === k ) }.
inject(0){ |sum, h| sum + h.second.max_by{ |h| h[:temperature] }[:temperature] }
=> 26.4
# 1) Group by day
puts json_data.
group_by{|h| Date.parse( h[:date] )}
{
Mon, 15 Aug 2016=>[
{:temperature=>22.4, :date=>"20160815-0345"},
{:temperature=>10.4, :date=>"20160815-1435"}
],
Thu, 01 Jan 2099=>[
{:temperature=>15.8, :date=>"20990101-0430"}
],
Tue, 16 Aug 2016=>[
{:temperature=>4, :date=>"20160816-0101"}
]
}
# 2) Remove those not within the last 30 days
puts json_data.
group_by{ |h| Date.parse(h[:date]) }.
reject{ |k, v| !( ((30.days.ago.to_date)..(Date.today)) === k ) }
{
Mon, 15 Aug 2016=>[
{:temperature=>22.4, :date=>"20160815-0345"},
{:temperature=>10.4, :date=>"20160815-1435"}
],
Tue, 16 Aug 2016=>[
{:temperature=>4, :date=>"20160816-0101"}
]
}
# 3) Showing what's happening inside the inject() block.
puts json_data.
group_by{ |h| Date.parse(h[:date]) }.
reject{ |k, v| !( ((30.days.ago.to_date)..(Date.today)) === k ) }.
inject(0){ |sum, h|
puts "h ==> #{h}";
puts "h.second ==> #{h.second}";
puts "h.second.max_by ==> #{h.second.max_by{ |h| h[:temperature] }[:temperature]}"
}
h ==> [
Mon, 15 Aug 2016,
[
{:temperature=>22.4, :date=>"20160815-0345"},
{:temperature=>10.4, :date=>"20160815-1435"}
]
]
h.second ==> [
{:temperature=>22.4, :date=>"20160815-0345"},
{:temperature=>10.4, :date=>"20160815-1435"}
]
h.second.max_by ==> 22.4
h ==> [
Tue, 16 Aug 2016,
[
{:temperature=>4, :date=>"20160816-0101"}
]
]
h.second ==> [
{:temperature=>4, :date=>"20160816-0101"}
]
h.second.max_by ==> 4