我正在尝试找到数组中几个哈希的平均值,这些哈希看起来像这样:
[{"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
我感激所有的帮助。谢谢!
total \ hash.length
。 (2) 你的哈希表只包含一个条目。因此,hash.length
将总是为1。 - user1934428