ruby - 比较类内 rand 变量的正确方法?

标签 ruby

在这个例子中:

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/

相关文章:

ruby-on-rails - 查找散列与散列数组的部分匹配

ruby-on-rails - 我如何判断是否使用了出售的 gem?

mysql - 通过ActiveRecord查询MySQL错误

ruby - 改进仅适用于实例方法吗?

ruby - 如何在不转换为数组的情况下按 Ruby 中的数值对哈希进行排序?

ruby - 我可以在 Heroku 应用程序中使用两种语言吗?

ruby - 用数组值反转散列

ruby - 无法从 Cucumber 2.3.2 中的 scene.file 获取场景的文件名

ruby - 随机 gsub 字符串 n 次

ruby open3 stdout 和 stdin 如何交互