Learn
Data Structures

Iterating Over Hashes

When iterating over hashes, we need two placeholder variables to represent each key/value pair.

restaurant_menu = {
  "noodles" => 4,
  "soup" => 3,
  "salad" => 2
}

restaurant_menu.each do |item, price|
  puts "#{item}: #{price}"
end
  1. In the example above, we create a new hash called restaurant_menu.
  2. Then, we loop through the restaurant_menu hash and assign the key to item and the value to price for each iteration.
  3. Finally, we puts out:
noodles: 4
soup: 3
salad: 2
Community Forums
Get help and ask questions in the Codecademy Forums
Report a Bug
If you see a bug or any other issue with this page, please report it here.