我正在创建一个 Die 类,它具有输出骰子编号的功能。它已被命名为 printout 和 output,但由于 NoMethodError,函数继续失败。这是我的代码:
class Die
def initialize()
@number = rand(7)
end
def output()
puts @number
end
def roll()
@number = rand(7)
end
end
Die.new.roll.output
这是我运行代码时的错误:
undefined method `output' for 2:Integer (NoMethodError)
有什么想法吗?
最佳答案
你必须这样调用:
die = Die.new
die.output # => 1
die.roll
die.output # => 3
首先,您需要将对象 (Die.new
) 实例化为变量 (die
)。
然后调用你的方法。
注意:最好使用rand(1..6)
在不使用变量的情况下,你能做的更好的是:
Die.new.output # => 3
不可能像您那样使用链式方法(或遵循 Martin Zinovsky 的答案)
关于ruby - NoMethodError 有方法时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51950735/