在ruby中的散列上调用each
时,您可以像这样将键和值很好地分开:
{ :a => 1, :b => 2, :c => 3 }.each do |key, value|
puts "key is #{key} and value is #{value}"
end
=========================
key is :a and value is 1
key is :b and value is 2
key is :c and value is 3
=> {:a=>1, :b=>2, :c=>3}
但是,使用inject
时,这似乎不起作用。
{ :a => 1, :b => 2, :c => 3 }.inject(0) do |result, key, value|
puts "key is #{key} and value is #{value}"
result + value
end
=========================
key is [:a, 1] and value is
TypeError: nil can't be coerced into Fixnum
在上面的简化示例中,我并不真正需要密钥,所以我可以只调用hash.values.inject
,但假设我需要两个,那么这个可怕的小屋是否有更简洁的方法来做到这一点?
{ :a => 1, :b => 2, :c => 3 }.inject(0) do |result, key_and_value|
puts "key is #{key_and_value[0]} and value is #{key_and_value[1]}"
result + key_and_value[1]
end
答案 0 :(得分:21)
看起来你需要:
{ :a => 1, :b => 2, :c => 3 }.inject(0) do |result, (key, value)|
puts "key is #{key} and value is #{value}"
result + value
end