2013-09-29 34 views
12

我有以下代碼:紅寶石,堆棧層次過深(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的方式工作?

回答

25

你下面的代碼

def price 
    @price = price # <~~ method name you just defined with `def` keyword. 
end 

創建從未stopable遞歸,.

如何讓這段代碼按照沒有attr_accessor的方式工作?

你需要寫爲

def price=(price) 
    @price = price 
end 
def price 
    @price 
end 
+2

'高清價格=(價格)'也未嘗不可。 – steenslag

+0

@steenslag是的你是對的! –

+0

謝謝,我猜爲了清晰起見,我會使用def price =(new_price)。 – daremkd

5

你需要做的:

@price = self.price 

到對象的屬性price和你的方法參數price區分。

0

read_attribute是你在找什麼

def price 
    @price = read_attribute(:price) 
end