Ruby:环回枚举器

标签 ruby enumerator

有没有办法在 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

关于Ruby:环回枚举器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19491924/

相关文章:

mysql - rake gem :install shows error (database is not migrating)/

c++ - C++中的构造函数中的枚举

ruby-on-rails - 为 has_many :through relationship in Rails 3 创建 Controller 和 View

ruby - 多个版本的 shebang

scala - 如何在 Play 2 中从 ReactiveMongo 返回 JSON 的枚举器

c++ - 是否可以转发声明要在派生类中使用的枚举类?

ruby - 在 Ruby 中表达无限枚举数 `(1..Inf)` 的常用快速方法是什么?

ruby - 是否有内置方法来检查#next 或#peek 是否会引发 StopIteration?

ruby - 在 Ruby 中解析表的最佳方法

ruby - 使用 EM-WebSocket 或 Goliath 的多个订阅者