Ruby Array each Method Tutorial

In this section, we will learn what the `each` method is and how to use it in Ruby.

What is Array each Method in Ruby?

The Array each method, is a type of method that takes a block and sends the elements of the array to that block. So basically the block will be run per each element of the array and so we can run any sort of instructions on the elements within the body of the block.

Array each Method Syntax:

array.each do

|element|

#instructions…

end

Array each Method Parameters

We pass a block to the `each` method and that will be called per each element of the array.

Array each Method return Value

The method will return a reference to the array itself.

Example: using Array each method in Ruby

arr = ["One","Two","Three","Four","Five","Six"]

arr.each do |element|

    puts element

end

Output:

One

Two

Three

Four

Five

Six

How does array each method work in Ruby?

In this example, you can see the elements of the array are passed to the block and we simply just printed those to the output stream.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies