Anton Khaybulaev
Anton Khaybulaev

Reputation: 89

Rails: Iterate through an array multiple times

I have an array, let's say it's

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

Also I have a loop:

boxes.each_with_index do |fruit, i|
  ... some code ...
  array[i]
end

I don't know how many boxes are. What I want to achieve is iterating through the array (from "apple" to "orange") as many times as it takes: apple, orange, banana, apple... and again.

I couldn't find a method that can help me to do this. Also, I thought about resetting a counter inside the loop but haven't succeeded as well.

What do you think would be the most elegant solution? Thanks.

Upvotes: 1

Views: 1164

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110645

I concur with @Ursus that cycle is probably best here, but you could also use Array#rotate!:

arr = [1,2,3]
a = arr.dup.rotate!(-1) #=> [3, 1, 2]

a.rotate!.first         #=> 1
a.rotate!.first         #=> 2
a.rotate!.first         #=> 3
a.rotate!.first         #=> 1

Upvotes: 2

Ursus
Ursus

Reputation: 30056

array_enumerator = array.cycle

And then, you can call array_enumerator.next any time you want. It goes in cycle.

See official ruby documentation for the #cycle method: https://ruby-doc.org/core-2.4.0/Array.html#method-i-cycle

Upvotes: 4

Related Questions