Iterating Over Hashes


Iterate over the matz hash and print each value to the console using puts .

Given Code:

matz = { “First name” => “Yukihiro”,
“Last name” => “Matsumoto”,
“Age” => 47,
“Nationality” => “Japanese”,
“Nickname” => “Matz”


matz.each do |key, value|
puts matz[key]

I don’t understand why the values (Yukihiro, Matsumoto, etc) instead of the key (First name, Last name, etc) get printed out when the code is matz[key]. Is puts matz[key] the same as puts value? Why is that?

1 Like

if you want the key, just do:

puts key

if we look at the ruby documentation for hashes (link):

Accessing a value in a Hash requires using its key:

puts grades["Jane Doe"] # => 10

that is what you do, you access the value by using the key, which is why you get the value

1 Like

Thanks for the help. Sometimes the official documentation is still too hard for me to understand.

Correct me if I’m wrong, but another example to understand hashes was:

Please get me the value that is associated with this key.

1 Like

There are plenty of examples on the internet

but do you now understand why you get the value?

I believe so. Hashes are like dictionaries and we use them to get values from keys. The concept itself was easy to understand, but I had trouble understanding the syntax. Thanks for the help.

1 Like