3
有没有办法在Ruby中循环回枚举器?鉴于这段代码:Ruby:循环返回枚举器
a=[1,2,3]
a.to_enum
a.next => 1
a.next => 2
a.next => 3
a.next => 1
我怎样才能让next
方法返回的第一个元素时,枚举到达最后一个元素?
有没有办法在Ruby中循环回枚举器?鉴于这段代码:Ruby:循环返回枚举器
a=[1,2,3]
a.to_enum
a.next => 1
a.next => 2
a.next => 3
a.next => 1
我怎样才能让next
方法返回的第一个元素时,枚举到达最后一个元素?
您可以使用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
你也可以使用rewind
Enumerator.html#rewind
a.rewind
完全一样的问题,我问前段时间how-to-point-to-first-element-when-object-next-reached-the-end
嗨THX救了我的一天,但如何能我得到指针指向的当前值? –
@KitHo使用['Enumerator#peek'](http://ruby-doc.org/core-2.0.0/Enumerator.html#method-i-peek),例如'enum = a.cycle; enum.peek' –
docs说:返回枚举器中的下一个对象,但不会向前移动内部位置。如果该位置已经结束,则会触发StopIteration。 有时我只想检查内部指针指向的当前值。 –