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

each and map on Hashes

each and map on a hash go through every key and value pair, like reading every entry in a phone book. each does something with them, while map builds a new list from them.

In this page:

  1. each and map on Hashes
Syntax
ruby
hash.each { |key, value| # body }
result = hash.map { |key, value| expression }

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using map on a hash and expecting a hash back, when it returns an array; add .to_h.
  2. Writing a block with one parameter |pair| and expecting the key only, when it receives [key, value].
  3. Changing a hash while iterating it, which raises an error when keys are added.
🔒

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.