我有一系列哈希设置如下:
array = [
{"1" => 1, "2" => 2, "3" =>3},
{"1" => 1, "2" => 2, "3" =>3},
{"1" => 1, "2" => 2, "3" =>3}
]
我试图找到一种方法来平衡所有哈希的值与关键"1"
,例如。
有人可以帮忙吗?
考虑到Ruby版本,yield_self(别名)可能会起作用:
[{ "1" => 10, "2" => 2, "3" =>3 },
{ "1" => 43, "2" => 2, "3" =>3 },
{ "1" => 4, "2" => 2, "3" =>3 }].map { |hash| hash.fetch('1', 0) }.then { |arr| arr.sum.fdiv(arr.size) }
# 19.0
(10 + 43 + 4) / 3 = 19.0
,不是你的例子,而不仅仅是1 + 1 + 1。
Array现在有一个sum
方法,需要一个块。它基本上总结了块返回的内容:
array = [{"1" => 0, "2" => 2, "3" =>3}, {"1" => 1, "2" => 4, "3" =>6}, {"1" => 2, "2" => 6, "3" =>9}]
array.sum{|h| h['1']}.fdiv(array.size)
我会做这样的事情:
array = [{"1" => 1, "2" => 2, "3" =>3},{"1" => 1, "2" => 2, "3" =>3},{"1" => 1, "2" => 2, "3" =>3}]
array.map { |hash| hash['1'] }.inject { |sum, el| sum + el }.to_f / array.size
#=> 1.0
在本例中,array.map { |hash| hash['1'] }
使用密钥'1'
([1,1,1]
)提取所有元素的值。而.inject{ |sum, el| sum + el }.to_f / array.size
计算平均值。
给定数组(我更改了值以便于调试):
array = [{"1" => 0, "2" => 2, "3" =>3}, {"1" => 1, "2" => 4, "3" =>6}, {"1" => 2, "2" => 6, "3" =>9}]
此代码将每个键映射到值的平均值:
array.each_with_object(Hash.new{ |k,v| k[v] = [ ]}) { |h, hh| h.each { |k,v| hh[k] << v } }.transform_values { |k| k.sum.to_f/k.size }
#=> {"1"=>1.0, "2"=>4.0, "3"=>6.0}
array_data = [
{"1" => 1, "2" => 2, "3" =>3},
{"1" => 1, "2" => 2, "3" =>3},
{"1" => 1, "2" => 2, "3" =>3}
]
class Hash
def get_first
self['1']
end
end
class Array
def avg
sum / size
end
end
avg = array_data.map(&:get_first).avg