我试图以递归方式递增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)
答案 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