0
0
RubyHow-ToBeginner · 3 min read

How to Use each in Ruby: Simple Guide with Examples

In Ruby, each is a method used to loop through elements of a collection like an array or hash. You pass a block to each that runs for every element, letting you work with each item one by one.
📐

Syntax

The each method is called on a collection, followed by a block that takes one or more parameters representing each element. The block contains the code to execute for each element.

Example syntax for an array:

collection.each do |element|
  # code using element
end

For a hash, you can use two parameters for key and value:

hash.each do |key, value|
  # code using key and value
end
ruby
array = [1, 2, 3]
array.each do |num|
  puts num
end
Output
1 2 3
💻

Example

This example shows how to use each to print every item in an array and then every key-value pair in a hash.

ruby
fruits = ['apple', 'banana', 'cherry']
fruits.each do |fruit|
  puts "I like #{fruit}"  
end

prices = { apple: 100, banana: 50, cherry: 75 }
prices.each do |fruit, price|
  puts "#{fruit} costs #{price} cents"
end
Output
I like apple I like banana I like cherry apple costs 100 cents banana costs 50 cents cherry costs 75 cents
⚠️

Common Pitfalls

One common mistake is forgetting to provide a block to each, which causes an error or unexpected behavior. Another is using each on an object that does not support it, like a number.

Also, modifying the collection inside the each block can lead to confusing results.

ruby
wrong = [1, 2, 3]
# This will cause an error because no block is given
# wrong.each

# Correct usage:
wrong.each do |num|
  puts num
end
Output
1 2 3
📊

Quick Reference

  • Use each to loop over arrays, hashes, and other collections.
  • Pass a block with parameters for elements (and keys/values for hashes).
  • Do not modify the collection inside the block to avoid unexpected behavior.
  • Returns the original collection, so you can chain methods if needed.

Key Takeaways

Use each to run code for every element in a collection like an array or hash.
Always provide a block with parameters to access each element inside each.
each returns the original collection, allowing method chaining.
Avoid changing the collection inside the each block to prevent bugs.
each works only on objects that include the Enumerable module, like arrays and hashes.