可枚举循环上的计数迭代 [英] Count iteration on the Enumerable cycle

查看:35
本文介绍了可枚举循环上的计数迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to use an enumerator like [1,2,3].cycle and count how many times I've gone through the iterations. [1,2,3].cycle.count creates an infinite loop and doesn't bring the iteration count. I'm playing a card game, and it cycles through the players. It's easy in the game to say:

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

它有效.但我想知道如何更改 count 或仅将 iter 添加到带有 cycle 的枚举器中,如下所示:

and it works. But I would like to know how to change count or add iter only for enumerators with cycle into something like this:

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

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

Since everything in Ruby is an Object, I should be able to create functions within functions as this case works:

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

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

How can I overwrite the behaviour of count only within a cycle enumerator or at least create a working method iter within the cycle Enumerator?

推荐答案

你可以很容易地把类似的东西放在一起.类似的东西

You can put something like that together fairly easily. Something like

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    

这篇关于可枚举循环上的计数迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆