How to use the Ruby each_with_index Method

09/22/2021

Contents

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

The each_with_index Method

The each_with_index method is a built-in Ruby method that iterates over an enumerable object, passing each element and its index to the block of code provided. This method is particularly useful when you need to perform some operation on each element of an array or other collection and also need to keep track of the index of the element.

The syntax for the each_with_index method is as follows:

enumerable.each_with_index do |element, index|
  # code to be executed for each element and its index
end

Here, enumerable is the object to be iterated over, and elementand index are the parameters that will be passed to the block of code. The block of code can contain any valid Ruby code, including conditional statements, loops, and other methods.

For example, let’s say you have an array of strings representing different fruits, and you want to print each fruit and its index:

fruits = ["apple", "banana", "orange", "pear"]

fruits.each_with_index do |fruit, index|
  puts "#{index}: #{fruit}"
end

In this example, the each_with_index method iterates over the fruits array and passes each fruit and its index to the block of code. The block of code uses string interpolation to print each fruit and its index to the console.

The output of this code would be:

0: apple
1: banana
2: orange
3: pear

You can also use the each_with_index method to modify the elements of the enumerable object. For example, let’s say you have an array of numbers, and you want to add 10 to each number:

numbers = [1, 2, 3, 4]

numbers.each_with_index do |number, index|
  numbers[index] += 10
end

puts numbers.inspect

In this example, the each_with_index method iterates over the numbers array and passes each number and its index to the block of code. The block of code modifies each element of the array by adding 10 to it. Finally, the inspect method is called on the numbers array to print the modified array to the console.

The output of this code would be:

[11, 12, 13, 14]