Join my Laravel for REST API's course on Udemy 👀

Iterate through a hash in Ruby

August 15, 2022  ‐ 1 min read

Looping over the contents of a hash in Ruby is quite similar to looping over the contents of an array. We can make use of the .each method, which is actually an alias for the .each_pair method, that returns an enumerator.

The key and value of the hash contents are passed to the enumerator.

hash = {
  python: 'Django',
  php: 'Laravel',
  ruby: 'Ruby on Rails',
}

hash.each do |key, value|
  puts "Write #{key} with #{value}"
end

#=> Write python with Django
#=> Write php with Laravel
#=> Write ruby with Ruby on Rails

Besides the .each method we have other options available to us as well:

  • each_key to loop over the keys in a hash.
  • each_value to loop over the values in a hash.
  • each_with_index to loop over the key and values in a hash with a corresponding index.