How To Loop Through An Array In Ruby

In this blog post, we will learn how to loop through an array in Ruby. Arrays are a commonly used data structure, and iterating over their elements is a fundamental task in programming. Ruby provides several methods to loop through arrays, and in this post, we’ll explore some of the most popular ones.

Method 1: Using each

The each method is one of the most straightforward ways to loop through an array in Ruby. This method iterates over each element of the array, allowing you to perform actions on each element. Here’s an example of how to use the each method:


array = [1, 2, 3, 4, 5]

array.each do |element|
  puts element
end
    

In this example, the each method iterates over the array and outputs each element. The |element| syntax inside the do block is a variable that holds the current element of the array during each iteration.

Method 2: Using for Loop

Another way to loop through an array in Ruby is using a for loop. Here’s an example of how to use a for loop to iterate over an array:


array = [1, 2, 3, 4, 5]

for element in array
  puts element
end
    

In this example, the for loop iterates over the array and outputs each element, just like the each method. The variable element represents the current element in the array during each iteration.

Method 3: Using each_with_index

Sometimes, you might want to loop through an array and have access to both the current element and its index. In this case, you can use the each_with_index method. Here’s an example:


array = ["apple", "banana", "cherry"]

array.each_with_index do |element, index|
  puts "#{index}: #{element}"
end
    

In this example, the each_with_index method iterates over the array, and the do block has two variables: element and index. The element variable holds the current element, while the index variable holds the current index of the element in the array. The output will display the index followed by the element.

Conclusion

Looping through arrays in Ruby is a fundamental task, and there are several ways to accomplish this. In this blog post, we explored three popular methods: each, for loop, and each_with_index. Choose the method that best suits your needs and happy coding!