更新:测试和工作
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