gpt4 book ai didi

Ruby,堆栈级别太深(SystemStackError)

转载 作者:数据小太阳 更新时间:2023-10-29 06:37:25 26 4
gpt4 key购买 nike

我有以下代码:

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) 错误。这是怎么回事?我知道我可以将 Integer(price*100 + 0.5) 替换为 @price 而不是方法调用价格,但出于 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

关于Ruby,堆栈级别太深(SystemStackError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19082772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com