0
0
RubyHow-ToBeginner · 3 min read

How to Iterate Over Hash in Ruby: Syntax and Examples

In Ruby, you can iterate over a hash using the each method, which yields each key-value pair to a block. Use hash.each { |key, value| ... } to access keys and values inside the block.
📐

Syntax

The basic syntax to iterate over a hash uses the each method. It passes two variables to the block: one for the key and one for the value.

  • hash: your hash variable
  • each: method to loop over each pair
  • key, value: block variables representing each key and its value
ruby
hash.each do |key, value|
  # code using key and value
end
💻

Example

This example shows how to print each key and value from a hash using each. It demonstrates accessing both parts of each pair.

ruby
person = { name: "Alice", age: 30, city: "New York" }
person.each do |key, value|
  puts "#{key}: #{value}"
end
Output
name: Alice age: 30 city: New York
⚠️

Common Pitfalls

One common mistake is using only one block variable, which will receive an array of [key, value] instead of separate variables. This can cause confusion when accessing keys or values.

Another pitfall is modifying the hash while iterating, which can lead to unexpected behavior.

ruby
hash = { a: 1, b: 2 }
hash.each do |pair|
  puts pair[0]  # key
  puts pair[1]  # value
end

# Better way:
hash.each do |key, value|
  puts key
  puts value
end
Output
a 1 b 2 a 1 b 2
📊

Quick Reference

  • each: iterate over key-value pairs
  • each_key: iterate over keys only
  • each_value: iterate over values only

Key Takeaways

Use each with two block variables to access keys and values separately.
Avoid using a single block variable unless you handle the key-value pair as an array.
Do not modify a hash while iterating over it to prevent errors.
Use each_key or each_value if you only need keys or values.
Iterating over hashes is simple and efficient with Ruby's built-in methods.