在这个例子中:
class random
randNum = rand(1)
randNum2 = rand(1)
end
if randNum == randNum2
puts("the numbers you rolled matched")
else
puts("the numbers you rolled did not match")
end
我收到的错误是:
<main>': undefined local variable or method
randNum' for main:Object (NameError)
你的意思?兰特
比较它们的正确方法是什么?
最佳答案
您在类中定义 randNum
。然后您尝试在类外调用它。
如果这只是一个脚本,您应该使用:
randNum = rand(6)
randNum2 = rand(6)
if randNum == randNum2
puts("the numbers you rolled matched")
else
puts("the numbers you rolled did not match")
end
但是,如果您想使用类,则可以使用以下方法:
class Random
attr_accessor :rand_1, :rand_2
def initialize
self.rand_1 = rand(6)
self.rand_2 = rand(6)
end
def match?
rand_1 == rand_2
end
def does_match?
if match?
puts("the numbers you rolled matched")
else
puts("the numbers you rolled did not match")
end
end
end
generator = Random.new
generator.does_match?
另请注意,rand(1)
将始终返回 0,因此您可能只想使用 rand
或定义不同的参数,例如。 6
关于ruby - 比较类内 rand 变量的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57389091/