Help on 2 iterating over hashes


#1

matz = { "First name" => "Yukihiro",
"Last name" => "Matsumoto",
"Age" => 47,
"Nationality" => "Japanese",
"Nickname" => "Matz"
}
matz.each do |key,value|
puts key, matz[key]
end


#2

What error are you getting?


#3

i solve it,thanks :grinning:


#4

I'm stuck here too,
this is my code
matz = { "First name" => "Yukihiro",
"Last name" => "Matsumoto",
"Age" => 47,
"Nationality" => "Japanese",
"Nickname" => "Matz"
}

matz.each do |matz| puts "#{matz}:"
end

this is whats on the console,

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

the "error" says - It looks like you didn't print Yukihiro using puts.

but surely i have... because its on the console, where am i going wrong. Ive been taking notes and my previous hashes have worked fine or so i thought.

EDIT; for some reason the forum itself isnt printing
"First name", "Yukihiro":
["Last name", "Matsumoto"]: <---> this is on my console if that makes any sense haha


#5

EDIT 2: I've worked it out although I don't really understand it, if anyone is willing to shed some light?

my final code - matz.each do |key, value| puts value, matz[value]
end


#6

You can also use,

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

matz.each {|x,y| puts "#{y}"}


#9

because this dont work
matz = { "First name" => "Yukihiro",
"Last name" => "Matsumoto",
"Age" => 47,
"Nationality" => "Japanese",
"Nickname" => "Matz"
}
puts matz


#10

Copying the example I used below which works.

matz = { "First name" => "Yukihiro",
"Last name" => "Matsumoto",
"Age" => 47,
"Nationality" => "Japanese",
"Nickname" => "Matz"
}
matz.each do |ask, ans|
puts matz[ask]
end