I am trying to recursively increment @counter instance variable of a CounterClass, but every time #incrementer method is called @counter is set to 0 again, resulting in a infinite recursion.
我试图以递归方式递增CounterClass的@counter实例变量,但每次调用#incrementer方法时@counter再次设置为0,从而导致无限递归。
What am I doing wrong? (I guess that @counter variable is never updated)
我究竟做错了什么? (我猜@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 个解决方案
#1
0
You can do something like this:
你可以这样做:
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
#1
0
You can do something like this:
你可以这样做:
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