DEV Community

Thieu Luu
Thieu Luu

Posted on

The .each method with do - end blocks and pipes ||

What is the .each method?
The .each method is an iterator method that is used to iterate over elements in an enumerable object, such as an array, hash, or range. It allows you to perform a specific action for each element in the collection.

Using .each with do - end blocks:

# Using .each with a do - end block to iterate over elements in an array
numbers = [1, 2, 3, 4, 5]

numbers.each do |num|
  puts num * 2
end

Enter fullscreen mode Exit fullscreen mode

In this example, the do - end block is used to define the code that will be executed for each element in the numbers array. The variable num represents each individual element during each iteration.

Using .each with pipes ('||'):
You can also use pipes (| |) to specify the block parameters. The following example achieves the same result as the previous one:

# Using .each with pipes (| |) to iterate over elements in an array
numbers = [1, 2, 3, 4, 5]

numbers.each { |num| puts num * 2 }

Enter fullscreen mode Exit fullscreen mode

In this example, the block is written in a single line using braces ({ }). The variable num is still used to represent each element during iteration.

How and when to use .each method?

1) Iterating Over Arrays:

fruits = ["apple", "banana", "orange"]
fruits.each { |fruit| puts "I love #{fruit}" }

Enter fullscreen mode Exit fullscreen mode

2) Iterating Over Hashes:

person = { name: "John", age: 30, city: "New York" }
person.each { |key, value| puts "#{key}: #{value}" }

Enter fullscreen mode Exit fullscreen mode

3) Performing Actions on Each Element:

numbers = [1, 2, 3, 4, 5]
squared_numbers = []
numbers.each { |num| squared_numbers << num**2 }

Enter fullscreen mode Exit fullscreen mode

4) Iterating Over a Range:

(1..5).each { |num| puts num }

Enter fullscreen mode Exit fullscreen mode

Top comments (0)