When calling each on a hash in ruby, you can get the key and value nicely separated like this:
{ :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}
However this doesn’t seem to work when using 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
In the simplified example above I don’t really need the keys so I could just call hash.values.inject, but assuming I need both, is there a cleaner way to do this than this horrible bodge?
{ :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
It looks like you need: