【问题标题】:Ruby, stack level too deep (SystemStackError)Ruby,堆栈级别太深(SystemStackError)
【发布时间】:2013-10-05 15:22:25
【问题描述】:

我有以下代码:

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

【问题讨论】:

    标签: ruby


    【解决方案1】:

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

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

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

    def price
      @price = price
    end
    

    【讨论】:

      【解决方案2】:

      read_attribute 就是你要找的东西

      def price 
        @price = read_attribute(:price)
      end
      

      【讨论】:

        【解决方案3】:

        你下面的代码

        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
        

        【讨论】:

        • def price=(price) 也可以。
        • 谢谢,为了清楚起见,我想我会使用 def price=(new_price)。
        【解决方案4】:

        你需要做的:

        @price = self.price
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-10
          • 2014-10-25
          • 2017-08-19
          • 1970-01-01
          • 2017-05-21
          • 2014-08-23
          相关资源
          最近更新 更多