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:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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
- Using
mapon a hash and expecting a hash back, when it returns an array; add.to_h. - Writing a block with one parameter
|pair|and expecting the key only, when it receives[key, value]. - 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: