Ruby, stack level too deep (SystemStackError)

前端 未结 4 1813
时光取名叫无心
时光取名叫无心 2021-02-18 15:40

I have the following code:

class BookPrice
  attr_accessor :price
  def initialize(price)
    @price = price
  end

  def price_in_cents
    Integer(price*100 +          


        
相关标签:
4条回答
  • 2021-02-18 16:11

    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?

    You need to write as

    def price=(price)
      @price = price
    end
    def price
      @price 
    end
    
    0 讨论(0)
  • 2021-02-18 16:12

    One general reason this can happen is if you have some method that calls itself recursively (i.e. calls itself inside itself, which causes an infinite loop).

    That's the problem I had that led to the error message.

    In your case that's what's happening here:

    def price
      @price = price
    end
    
    0 讨论(0)
  • 2021-02-18 16:13

    read_attribute is what you are looking for

    def price 
      @price = read_attribute(:price)
    end
    
    0 讨论(0)
  • 2021-02-18 16:15

    You need to do:

    @price = self.price
    

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

    0 讨论(0)
提交回复
热议问题