How to iterate over an array in Ruby
Array implements an enumerable each which allows you to iterate over an array.
my_array = [1,44,32,’asc’,’ere’]
my_array.each { |item| puts item}
You can use collect method of Enumerable Class if you want to transform an array
my_array.collect { |item| item*3}
In case you want to replace values in an existing array, you can use destructive property of the collect method by adding an exclamation point at the end
my_array.collect! { |item| item.upcase}
Important to note that an Array class includes Enumerable module. As a result, such methods are each, collect are available for use.
In case you want to get an array element with its corresponding index, you can use Enumerable module method called each_with_index.
my_array.each_with_index do |item, index|
puts “Value #{item} with index #{index}
end
In addition to repaying on Enumerable module methods, an Array class implements several generators
my_array.reverse_each {|item| puts item}
There are several other useful generators available in the Ruby for an array class such as .upto, .step. There are other iterators, commonly found in several programming languages, available to use including for, while, until.
Here is a list of examples that help you to see how each of these iterators can be used.
for index in (0…my_array.length)
puts “Value #{my_array[index]}”
end
while index < my_array.length
puts “Value #{my_array[index]}”
index+=1
end
unitl index == my_array.length
puts “Value #{my_array[index]}”
index+=1
end