Serjik Serjik - 6 months ago 10
Ruby Question

ruby print hash values in iteration

This is happening and it seems weird to me.

The following code prints nothing but blank lines:

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

matz.each do |k|
puts matz[k]
end


if I change that to

matz.each do |k|
puts k
puts matz[k]
end


works

also

matz.each do |k,v|
puts matz[k]
end


works

Anybody has got any explain please

Answer

In:

matz.each do |k|
  puts  matz[k]
end

each k will be an array that represents a key-value pair such as ["First name", "Yukihiro"]. Since none of these pairs a key of the hash matz, puts matz[k] is the same as puts nil.

Comments