Cover by Leonard Richardson, Lucas Carlson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

5.7. Iterating Over a Hash

Problem

You want to iterate over a hash's key-value pairs as though it were an array.

Solution

Most likely, the iterator you want is Hash#each_pair or Hash#each. These methods yield every key-value pair in the hash:

	hash = { 1 => 'one', [1,2] => 'two', 'three' => 'three' }

	hash.each_pair { |key, value| puts "#{key.inspect} maps to #{value}"}
	# [1, 2] maps to two
	# "three" maps to three
	# 1 maps to one

Note that each and each_pair return the key-value pairs in an apparently random order.

Discussion

Hash#each_pair and Hash#each let you iterate over a hash as though it were an array full of key-value pairs. Hash#each_pair is more commonly used and slightly more efficient, but Hash#each is more array-like. Hash also provides several other iteration methods that can be more efficient than each.

Use Hash#each_key if you only need the keys of a hash. In this example, a list has been stored as a hash to allow for quick lookups (this is how the Set class works). The values are irrelevant, but each_key can be used to iterate over the keys:

	active_toggles = { 'super' => true, 'meta' => true, 'hyper' => true }
	active_toggles.each_key { |active| puts active }
	# hyper
	# meta
	# super

Use Hash#each_value if you only need the values of a hash. In this example, each_value is used to summarize the results of a survey. Here it's the keys that are irrelevant:

 favorite_colors = { 'Alice' => :red, 'Bob' => :violet, 'Mallory' => :blue, 'Carol' => :blue, 'Dave' => :violet } summary ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required