我想使用一个像[1,2,3].cycle这样的枚举器,并计算我经过迭代的次数。[1,2,3].cycle.count创建一个无限循环,但不会带来迭代计数。我在玩纸牌游戏,它在玩家之间循环。在游戏中很容易说:

@round = 0
if @turn == 1
  @round += 1
end

而且有效。但我想知道如何将count或只为iter的枚举数添加cycle更改为如下内容:
module Enumerable
  def cycle
    super
    def count
      puts "Hi"
    end
  end
end

由于ruby中的所有内容都是一个对象,因此在这种情况下,我应该能够在函数中创建函数:
def x
  def y
    puts 1
  end
end
x.y
# => 1

如何仅在count枚举数内覆盖cycle的行为,或者至少在iter枚举数内创建工作方法cycle

最佳答案

你可以很容易地把那样的东西拼起来。有点像

class Iter < Array
  attr_reader :iteration

  def initialize(*args)
    super(*args)
    @pointer = 0
    @iteration = 1 # Current iteration
  end

  def next
    self[@pointer].tap {
      @pointer = (@pointer + 1) % size
      @iteration += 1 if @pointer == 0
    }
  end
end

iter = Iter.new [1,2,3]

7.times { puts 'iteration %d: %d' % [iter.iteration, iter.next] }

# iteration 1: 1
# iteration 1: 2
# iteration 1: 3
# iteration 2: 1
# iteration 2: 2
# iteration 2: 3
# iteration 3: 1

10-07 17:53