Ruby,堆栈级别太深(SystemStackError) [英] Ruby, stack level too deep (SystemStackError)

查看:43
本文介绍了Ruby,堆栈级别太深(SystemStackError)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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 替换为:

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

def price
  @price = price
end

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

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?

推荐答案

你下面的代码

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

创建永不停止的递归.

如何使此代码在没有 attr_accessor 的情况下正常工作?

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

你需要写成

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

这篇关于Ruby,堆栈级别太深(SystemStackError)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆