each and map on Hashes
In this page:
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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: