23

我有以下代码:

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 的情况下,如何使此代码按原样工作?

4

4 回答 4

35

您的以下代码

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
于 2013-09-29T20:13:26.647 回答
6

你需要做:

@price = self.price

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

于 2013-09-29T20:13:53.870 回答
2

read_attribute是你要找的

def price 
  @price = read_attribute(:price)
end
于 2015-02-10T21:23:33.803 回答
1

发生这种情况的一个普遍原因是,如果您有一些递归调用自身的方法(即在自身内部调用自身,这会导致无限循环)。

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

在你的情况下,这就是这里发生的事情:

def price
  @price = price
end
于 2020-12-19T17:18:26.417 回答