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。 有時我只想檢查內部指針指向的當前值。 –