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
Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.
Entries in a hash are often referred to as key-value pairs. This creates an associative representation of data. Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated.
It looks like you need:
{ :a => 1, :b => 2, :c => 3 }.inject(0) do |result, (key, value)|
puts "key is #{key} and value is #{value}"
result + value
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With