Ruby:在某些日期之间的散列数组中汇总值

时间:2011-05-04 20:40:29

标签: ruby arrays hash

我在Ruby中有一系列哈希:

array = [
  {:date => Wed, 04 May 2011 00:00:00 PDT -07:00,
   :value => 200}
  {:date => Wed, 04 May 2011 01:00:00 PDT -07:00,
   :value => 100}
  {:date => Tue, 03 May 2011 01:00:00 PDT -07:00,
   :value => 300}
  {:date => Tue, 03 May 2011 01:00:00 PDT -07:00,
   :value => 150}
]

我希望能够在每天内组合这些值,以便我有一个像这样的新数组:

array = [
  {:date => Wed, 04 May 2011 00:00:00 PDT -07:00,
   :value => 300}
  {:date => Tue, 03 May 2011 00:00:00 PDT -07:00,
   :value => 450}
]

白天搜索数组最理想的方法是什么?总结每天的值?

这是我最初的尝试:

entries = [
  {:date => Wed, 04 May 2011 00:00:00 PDT -07:00,
   :value => 200}
  {:date => Wed, 04 May 2011 01:00:00 PDT -07:00,
   :value => 100}
  {:date => Tue, 03 May 2011 01:00:00 PDT -07:00,
   :value => 300}
  {:date => Tue, 03 May 2011 01:00:00 PDT -07:00,
   :value => 150}
]

first_day = 29.days.ago.beginning_of_day
total_days = 30

day_totals = (0...total_days).inject([]) do |array, num|
    startat = first_day + num.day
    endat = startat.end_of_day

    total_value_in_day = entries.where("date >= ? and date <= ?", startat, endat).sum(:value)

    array << {:date => startat, :value => total_value_in_day}
end

我意识到我的错误是使用where方法,这是一种用于搜索对象的Rails方法,不能在数组上使用。所以我的主要问题是,有没有办法搜索有条件的数组或哈希值。

2 个答案:

答案 0 :(得分:5)

您可以遍历条目以创建新数组:

totals = Hash.new(0)
array.each do |entry|
  totals[entry[:date]] += entry[:value]
end

# Now totals will be something like this:
# => {"Wed, 04 May 2011" => 300, "Tue, 03 May 2011" => 450...}

# If you then want this in the same array format you started with:
new_array = totals.collect{ |key, value| {:date => key, :value => value} }
# => [{:date => "Wed, 04 May 2011", :value => 300}, {....}]

答案 1 :(得分:3)

对于1.9.2:

>> array.each_with_object(Hash.new(0)) { |el, hash| hash[el[:date]] += el[:value] } 
#=> {"Wed, 04 May 2011 00:00:00 PDT -07:00"=>200, "Wed, 04 May 2011 01:00:00 PDT -07:00"=>100, "Tue, 03 May 2011 01:00:00 PDT -07:00"=>450}

也适用于1.8:

>> array.inject(Hash.new(0)) { |hash, el| hash[el[:date]] += el[:value] ; hash } 
#=> {"Wed, 04 May 2011 00:00:00 PDT -07:00"=>200, "Wed, 04 May 2011 01:00:00 PDT -07:00"=>100, "Tue, 03 May 2011 01:00:00 PDT -07:00"=>450}