gpt4 book ai didi

ruby - Enumerable 循环上的计数迭代

转载 作者:数据小太阳 更新时间:2023-10-29 07:44:01 26 4
gpt4 key购买 nike

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

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

并且有效。但我想知道如何更改 count 或只为具有 cycle 的枚举器添加 iter 到这样的东西:

module Enumerable
def cycle
super
def count
puts "Hi"
end
end
end

由于 Ruby 中的一切都是对象,因此我应该能够在函数内创建函数,因为这种情况有效:

def x
def y
puts 1
end
end
x.y
# => 1

如何仅在 cycle 枚举器中覆盖 count 的行为,或者至少在 中创建一个工作方法 iter循环 枚举器?

最佳答案

您可以很容易地将类似的东西放在一起。有点像

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

关于ruby - Enumerable 循环上的计数迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24764323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com