— Ruby, Arrays, Loops — 1 min read
The most common way to iterate through an array in Ruby is using the each method. This method executes a block of code for each element in the array:
1numbers = [1, 2, 3, 4, 5]2numbers.each do |number|3 puts number4endIn this example, we have an array called numbers, and we use the each method to loop through it. For each element in the numbers array, the block of code within the do...end is executed, printing each number to the console.
map for TransformationWhen you need to transform each element of an array, the map method can be quite handy. It returns a new array containing the results of applying the given block to each element:
1original_array = [1, 2, 3, 4, 5]2transformed_array = original_array.map { |n| n * 2 }3puts transformed_arrayIn this case, the map method multiplies each element of the original array by 2, creating a new array called transformed_array. This method is useful when you want to perform a transformation on every element of the array without modifying the original array.
selectSometimes, you may need to iterate through an array and select specific elements based on a condition. The select method allows you to do just that:
1numbers = [1, 2, 3, 4, 5]2even_numbers = numbers.select { |n| n.even? }3puts even_numbersIn this example, the select method creates a new array containing only the even numbers from the original array.
If you need to access both the index and the value of each element in the array, you can use the each_with_index method:
1fruits = ['apple', 'banana', 'cherry']2fruits.each_with_index do |fruit, index|3 puts "#{index + 1}. #{fruit}"4endHere, the each_with_index method provides access to both the index and the value of each element, allowing us to display the position of each fruit in the list.