【发布时间】:2013-10-05 15:22:25
【问题描述】:
我有以下代码:
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,如何使此代码按原样工作?
【问题讨论】:
标签: ruby