3

Is there a way to loop back an enumerator in Ruby? Given this piece of code:

a=[1,2,3]
a.to_enum

a.next => 1
a.next => 2
a.next => 3
a.next => 1

How can I make the next method go back to the first element when the enumerator reached the last element?

0

2 Answers 2

8

You can use Enumerable#cycle:

a = [1, 2, 3]
enum = a.cycle  #=> #<Enumerator: [1, 2, 3]:cycle>

enum.next       #=> 1
enum.next       #=> 2
enum.next       #=> 3
enum.next       #=> 1
Sign up to request clarification or add additional context in comments.

4 Comments

Hi thx saving my day, but how can i get the current value that the pointer points to?
@KitHo use Enumerator#peek, e.g. enum = a.cycle; enum.peek
The docs said : Returns the next object in the enumerator, but doesn’t move the internal position forward. If the position is already at the end, StopIteration is raised. Sometime i just want to inspect what current value that the internal pointer is pointing to.
Normally you would just save it in a variable. Using peek you can acheive the same thing by just calling next after you have consumed the output, not before.
2

you can also use rewind Enumerator.html#rewind

a.rewind

Exactly same question I asked some time ago how-to-point-to-first-element-when-object-next-reached-the-end

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.