如何在Ruby中找到哈希数组的平均值

时间:2018-04-09 06:22:29

标签: arrays ruby hash average

我试图在数组中找到几个哈希的平均值,如下所示:

[{"path"=>"/abcd.com", "time"=>0.503},
 {"path"=>"/abcd.com", "time"=>0.765},
 {"path"=>"/abcd.com", "time"=>0.553}]

数组按路径分组,我想找到加载此路径所需的平均时间。

这是我到目前为止所做的:

 averages = grouped_data.each do |array|
   array.each do |hash|
     hash["time"].reduce(:+) \ hash.length
   end 
 end

我认为它不起作用,因为哈希中的时间是浮点数。所以我尝试了添加总计而不使用reduce,但total返回了0

 averages = grouped_data.each do |array|
   total = 0
   array.each do |hash|
     hash["time"] += total \ hash.length
   end 
   return total
 end

我感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个:

array = [{"path"=>"/sale.html", "time"=>0.503}, {"path"=>"/sale.html", "time"=>0.765}, {"path"=>"/sale.html", "time"=>0.553}]
average = array.map { |x| x["time"] }.sum / array.size # 0.6070

您也可以直接在数组中使用sum

average = array.sum { |x| x["time"] } / array.size # 0.6070

答案 1 :(得分:1)

对您的grouped_data结构做出假设,请验证。

grouped_data = [
                [
                 {"path"=>"/sale.html", "time"=>0.503},
                 {"path"=>"/sale.html", "time"=>0.765},
                 {"path"=>"/sale.html", "time"=>0.553}
                ],
                [
                 {"path"=>"/sales.html", "time"=>1.0},
                 {"path"=>"/sales.html", "time"=>1.0},
                 {"path"=>"/sales.html", "time"=>4.0}
                ]
               ]

如果您想要每条路径的平均值:

averages = grouped_data.map do |array|
 array.inject(0) do |sum, hash|
   sum + hash["time"]
   end.fdiv(array.size) 
end

 #=> [0.6070000000000001, 2.0]

或者路径和平均时间的哈希值:

avs = grouped_data.map { |array|
  array.inject({}) { |sum, hash|
    sum.merge(hash) { |k, o, n| k == 'time' ? o + n : o }
  }.map { |k, v| [k, k == 'time' ? v.fdiv(array.size) : v] }.to_h
}

 #=> [{ "path" => "/sale.html",  "time" => 0.6070000000000001 },
 #    { "path" => "/sales.html", "time" => 2.0 }]