Code Snippets
/

Ruby Hash Iteration Patterns

Ruby Hash Iteration Patterns

Ruby hashes preserve insertion order and play beautifully with the same `Enumerable` methods that work on arrays. This snippet covers the basic `each_pair` walk, transforming with `transform_keys` and `transform_values` (Ruby 2.4+/2.5+), and filtering plus reducing into a new hash. Use these to keep hash transformations as concise as their array counterparts.

Ruby
Easy
3 snippets
ruby-hashes
ruby-enumerables
iteration-patterns

1,167 views

11

ages = { ada: 36, linus: 54, margaret: 88 }

ages.each_pair do |name, age|
  puts "#{name} is #{age}"
end

# each_key and each_value give one half at a time.
ages.each_key { |k| print k, " " }
puts
ages.each_value { |v| print v, " " }
puts

puts "size=#{ages.size} keys=#{ages.keys.inspect}"

each_pair (alias each) yields key/value pairs in insertion order; Ruby has guaranteed hash ordering since 1.9. each_key and each_value are convenience iterators when you need only one side of each entry. keys and values return arrays you can chain further map/select on, but for one-shot loops the each-variants avoid building an intermediate array. Hash iteration order makes hashes a natural drop-in for ordered configuration maps; do not assume the same in Python before 3.7 or Java's HashMap.