Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Loop back Enumerator

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?

like image 999
TheOneTeam Avatar asked May 26 '26 02:05

TheOneTeam


2 Answers

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
like image 81
Stefan Avatar answered May 27 '26 16:05

Stefan


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

like image 44
Bala Avatar answered May 27 '26 16:05

Bala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!