← Back to Ruby Course | Chapter 5: Hashes | Lesson 3 of 7

each and map on Hashes

In this page:

  1. each and map on Hashes

each and map on Hashes

hash.each { |key, value| ... } iterates over every key-value pair, and hash.map { |key, value| ... } transforms each pair into a new array element (not a new hash, unless you follow up with .to_h). This mirrors the same enumeration style used on arrays. Both are the standard way to process every entry in a hash.

Note: map on a hash returns an array of the block's results -- chain .to_h afterward if you want a hash back.

Example: each and map on Hashes

markup
ages = { alice: 30, bob: 25, cara: 40 }

ages.each { |name, age| puts "#{name} is #{age}" }

doubled_ages = ages.map { |name, age| [name, age * 2] }.to_h
puts doubled_ages.inspect
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.