1

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.

1
  • This is a pure Ruby question so I recommend you strike "Rails" in the title and remove the "ruby-on-rails" tag. The Rails tag wastes time for members who only want to see Rails questions (i.e., who filter on Rails) and prevents members who have filtered out Rails questions from seeing your question. Also, I don't think "arrays" or "loops" are useful tags. I'd just have "ruby". Commented May 19, 2017 at 21:05

2 Answers 2

4
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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.