简体   繁体   English

如何制作无限枚举器

[英]How to make infinite enumerator

Suppose I have an array 假设我有一个数组

array = [1,2,3]

I need to create such a enumerator that will return values in cyclic manner: 我需要创建一个枚举器,该枚举器将以循环方式返回值:

array.next #=> 1
array.next #=> 2
array.next #=> 3
array.next #=> 1
array.next #=> 2
...

I believe there's a neat solution for that 我相信有一个整洁的解决方案

Array#cycle / Enumerable#cycle does what you are looking for: Array#cycle / Enumerable#cycle您的需求:

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

e.next             #=> 1
e.next             #=> 2
e.next             #=> 3
e.next             #=> 1
e.next             #=> 2

(1..3).cycle returns equivalent values. (1..3).cycle返回等效值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM