加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby,堆栈级别太深(SystemStackError)

发布时间:2020-12-16 19:52:09 所属栏目:百科 来源:网络整理
导读:我有以下代码: class BookPrice attr_accessor :price def initialize(price) @price = price end def price_in_cents Integer(price*100 + 0.5) endendb = BookPrice.new(2.20)puts b.price_in_cents 这一切都很好,产生220.但是当我更换第二行attr_accesso
我有以下代码:
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 with:

def price
  @price = price
end

我得到堆栈级太深(SystemStackError)错误.这是怎么回事?我知道我可以用@price替代Integer(price * 100 0.5)而不是方法调用价格,但是我想保持它的方式是为了OOP的原因.如何使这个代码的工作方式是没有attr_accessor?

解决方法

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

创造永远不会停止递归,.

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

你需要写作

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读