What is “each{ } method” in Ruby?

The each{} method allows one loop through the elements of an array to perform operations on them.

It is an enumerator function that allows you to iterate over elements of an array and returns an array.

Syntax

array_name.each{block}

Parameters

  • {block}: This is the loop that is executed. It takes a parameter which represents each element in the array and a function that will be performed on each element. See the example below:
[1,2,3,4].each{|elem| puts elem}
  • In the snippet above, the block takes elem as a parameter and prints the value to the console. elem here represents each element of the array. So the result will be:
1
2
3
4

Return value

It returns the array itself. For example the array above, [1,2,3,4] is what will be returned after each method is called on it.

Example

In the code below, the functionality of the each{} method will be applied to the elements of an array.

# create an array
array = ["Google", "Netflix", "Amazon", "Apple", "Meta"]
# use each method
a = array.each {|elem| puts elem}

From the code above, the each{} method was used to loop through the array array. As it looped, it printed each element in the array.

Now, let’s take it further. Let’s loop through the array and print the first character of each element.

# create an array
array = ["Google", "Netflix", "Amazon", "Apple", "Meta"]
# use each method
a = array.each {|elem| puts "#{elem} = #{elem[0,1]}" }

Free Resources