我有以下代码:
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)错误。这是怎么回事?我知道我可以用 @price 而不是方法调用价格替换 Integer(price*100 + 0.5),但出于 OOP 的原因,我想保持原样。在没有 attr_accessor 的情况下,如何使此代码按原样工作?