Ruby,堆栈级别太深(SystemStackError)

我有以下代码:

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:价格与:

 def price @price = price end 

我的堆栈级别太深(SystemStackError)错误。 这是怎么回事? 我知道我可以用@price替换Integer(价格* 100 + 0.5)而不是方法调用价格,但是我想保持它与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 

你需要这样做:

 @price = self.price 

区分对象属性price和方法参数price

read_attribute是你要找的

 def price @price = read_attribute(:price) end