Ruby,堆栈级别太深(SystemStackError)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19082772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:12:55  来源:igfitidea点击:

Ruby, stack level too deep (SystemStackError)

ruby

提问by daremkd

I have the following code:

我有以下代码:

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

This all works well and produces 220. But when I replace the second line attr_accessor :price with:

这一切都运行良好并产生 220。但是当我将第二行 attr_accessor :price 替换为:

def price
  @price = price
end

I get stack level too deep (SystemStackError) error. What's going on? I know I can replace Integer(price*100 + 0.5) with @price instead of the method call price, but I want to keep it the way it is for OOP reasons. How can I make this code work the way it is without attr_accessor?

我得到堆栈级别太深 (SystemStackError) 错误。这是怎么回事?我知道我可以用 @price 而不是方法调用 price 替换 Integer(price*100 + 0.5) ,但由于 OOP 的原因,我想保持它的样子。我怎样才能让这段代码在没有 attr_accessor 的情况下工作?

回答by Arup Rakshit

Your below code

你下面的代码

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

Creates never stopable recursion,.

创建永不停止的递归,。

How can I make this code work the way it is without attr_accessor?

我怎样才能让这段代码在没有 attr_accessor 的情况下工作?

You need to write as

你需要写成

def price=(price)
  @price = price
end
def price
  @price 
end

回答by Autumnsault

You need to do:

你需要做:

@price = self.price

to differentiate between your object attribute priceand your method parameter price.

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

回答by Maged Makled

read_attributeis what you are looking for

read_attribute是你要找的

def price 
  @price = read_attribute(:price)
end