Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to separate out key and value of a hash when using inject?

Tags:

ruby

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
like image 365
Russell Avatar asked Nov 04 '11 10:11

Russell


People also ask

Can a hash key have multiple values?

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.

What is key and value in hash?

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.


1 Answers

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
like image 114
ControlPower Avatar answered Sep 28 '22 00:09

ControlPower