Skip to content

How to iterate over an array in Ruby

Last updated on January 28, 2021

Each construct provides an easy way to iterate over arrays and hash. each loop will continue until it has gone through every item in the array.

We have an associative array that stores the names of fruits. We want to print out every fruit’s name.

Looping over a Array

fruits= ['orange', 'pear', 'banana']

# without indexes
fruits.each do |fruit|
    puts fruit
end

# with indexes
fruits.each_with_index do |fruit, i|
    puts i, fruit
end
0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments