我有以下代码:
class BookPrice
attr_accessor :price
def initialize(price)
@price = price
end
def price_in_cents
Integer(price*100 + 0.5)
end
end
b = BookPrice.new(2.20)
puts b.price_in_cents
这一切都运行良好并产生 220。但是当我将第二行 attr_accessor :price 替换为:
def price
@price = price
end
我收到堆栈级别太深(SystemStackError)错误。这是怎么回事?我知道我可以将 Integer(price*100 + 0.5) 替换为 @price 而不是方法调用价格,但出于 OOP 原因,我想保持原样。在没有 attr_accessor 的情况下,如何使该代码按原样工作?
你的下面的代码
def price
@price = price # <~~ method name you just defined with `def` keyword.
end
创建永不停止的递归。
在没有 attr_accessor 的情况下,如何使该代码按原样工作?
你需要写成
def price=(price)
@price = price
end
def price
@price
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)