尝试创建递归计数器时的无限递归

时间:2017-10-08 14:09:48

标签: ruby

我试图以递归方式递增CounterClass的@counter实例变量,但每次调用#incrementer方法时@counter再次设置为0,导致无限递归。

我做错了什么? (我猜@counter变量永远不会更新)

class CounterClass
  attr_accessor :counter

  def initialize
    @counter = 0
  end
end

def incrementer(arg)
  cc ||= CounterClass.new

  cc.counter += 1
  p cc.counter
  incrementer(cc) unless cc.counter == 10
end
incrementer(CounterClass.new)

1 个答案:

答案 0 :(得分:0)

您可以这样做:

class CounterClass
  attr_accessor :counter

  def initialize
    @counter = 0
  end

  def incrementer
    @counter += 1
    incrementer unless @counter == 10
  end
end

obj = CounterClass.new
obj.incrementer
p obj.counter #=> 10