OneBite.Dev - Coding blog in a bite size

loop array in Ruby

Code snippet on how to loop array in Ruby

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

array.each do |number|
  puts number
end

This code loop through an array, prints each element in the array into the console. First, we create a Ruby array with values 1, 2, 3, 4, 5 and assign it to a variable named ‘array’. Then, the ‘.each’ method is used on the ‘array’ variable. The ‘.each’ method allows us to loop through each element in the array with a given block of code. The block of code is given between the ‘do’ and ‘end’, and uses a ‘|pipe|’ symbol to represent each element. The code within the block is executed for each element in the array, and in this example, prints the number in the current element to the console using the ‘puts’ method.

ruby