Ruby,堆栈层级太深(SystemStackError)

27

我有以下代码:

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,而不是使用方法调用price,但出于面向对象编程(OOP)的原因,我希望保持现有的方式。如何在不使用attr_accessor的情况下使代码正常工作?
4个回答

40

您下面的代码

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

3
def price=(price) 也可以。 Translated: def price=(price) is also acceptable. - steenslag
谢谢,我猜我会使用def price =(new_price)为了清晰明了。 - daremkd

5

您需要做的是:

@price = self.price

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


2

出现这种情况的一个普遍原因是,您可能有一些调用自身递归的方法(即在其内部调用自身,从而导致无限循环)。

这就是我遇到的问题,导致了错误消息的出现。

在您的情况下,这就是发生的情况:

def price
  @price = price
end

1

read_attribute 是你要寻找的方法。

def price 
  @price = read_attribute(:price)
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接