How to Use the each Method in Ruby

09/18/2021

Contents

In this article, you will learn how to use the each method in Ruby.

The each method

In Ruby, the each method is used to iterate over elements in a collection and perform some operation on each element. Here’s how you can use the each method:

Iterate over an array:
array = [1, 2, 3, 4, 5]
array.each do |element|
  puts element
end

This will output:

1
2
3
4
5
Iterate over a hash:
hash = { "a" => 1, "b" => 2, "c" => 3 }
hash.each do |key, value|
  puts "#{key} => #{value}"
end

This will output:

a => 1
b => 2
c => 3
Use the each_with_index method to iterate over an array with the index:
array = [1, 2, 3, 4, 5]
array.each_with_index do |element, index|
  puts "Element #{index}: #{element}"
end

This will output:

Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
Use the each_line method to iterate over lines in a string:
string = "This is a string\nwith multiple lines\nin it."
string.each_line do |line|
  puts line
end

This will output:

This is a string
with multiple lines
in it.

These are just a few examples of how you can use the each method in Ruby. It’s a powerful method that allows you to perform operations on each element in a collection.