averaging values embedded in ruby hash

arrays, hash, ruby, ruby-on-rails

Solution

Hash[myhash.map { |k,v| [k, v.map(&:last).inject(:+) / v.size] }]
#=> {"2011-02-15"=>35, "2011-02-22"=>22, "2011-02-28"=>90}

Problem

I have an embedded hash, for which i need to calculate averages. I've already grouped them, successfully, (from ungrouped) but finding the average isn't working for me Here is the example hash data ``` myhash = {"2011-02-15"=>[["2011-02-15", 10], ["2011-02-15", 60]], "2011-02-22"=>[["2011-02-22", 22]], "2011-02-28"=>[["2011-02-28", 110],["2011-02-28", 70]]} ``` here is how I grouped them (they used to be just {k => v} ungrouped) ``` @r = @myhash.group_by(&:first) ``` I tried both solutions from this thread (What's the best way in Ruby to average sets in an array?) but neither worked. good question. I want the results to be averaged by date, so I can serve them up that way. ``` [{"2012-02-15" => 35"}, {"2012-02-22" => 22"}, {"2012-02-28" => 90"}] ```

Original source