【问题标题】:ruby function returns different boolean value in irb vs repl.itruby 函数在 irb 和 repl.it 中返回不同的布尔值
【发布时间】:2016-12-13 14:26:42
【问题描述】:

我编写了以下函数来检查一个数字是否为素数:

def is_prime?(number)
  arr = (2..number).to_a.select {|m| number % m == 0}
  arr.length == 1 ? true : false
end

当传递 4 或 9 作为 irb 中的数字时,它正确返回 false。但是,在 repl.it 中,这些计算结果为 true。

这是我在 repl.it 上运行的测试代码:

puts("\nTests for #is_prime?")
puts("===============================================")
puts('is_prime?(2) == true: ' + (is_prime?(2) == true).to_s)
puts('is_prime?(3) == true: ' + (is_prime?(3) == true).to_s)
puts('is_prime?(4) == false: ' + (is_prime?(4) == false).to_s)
puts('is_prime?(9) == false: ' + (is_prime?(9) == false).to_s)
puts("===============================================")

及其输出:

Tests for #is_prime?
===============================================
is_prime?(2) == true: true
is_prime?(3) == true: true
is_prime?(4) == false: true
is_prime?(9) == false: true
===============================================
What could be causing this variation?

【问题讨论】:

  • 您能“分享”您的 repl.it 会话吗?这就是我所看到的。 repl.it/Ck9M/0
  • 这里是我的 repl.it 会话的链接:repl.it/Br7y/452
  • 您的 repl 正在按预期工作。即使 4 和 9 评估为真,那是因为您正在检查它们是否为假。假 == 假为真
  • 我已将您的 repl 的代码和输出添加到问题中,还添加了指向 repl 的链接。我这样做是因为 SO 希望问题能够独立存在,而无需阅读 cmets(实际上,可以随时删除 cmets)。

标签: ruby primes irb


【解决方案1】:

我在 repl.it 上进行了尝试,结果 4 和 9 都为 false。

无论如何,您的代码有两个小改进: - 您可以直接在范围上调用select,而无需将其转换为数组 - 可以返回表达式本身的值,无需指定真假

def is_prime?(number)
  arr = (2..number).select {|m| number % m == 0}
  arr.length == 1
end

【讨论】:

    【解决方案2】:

    您对测试的输出感到困惑,它既报告了函数的预期结果,又报告了函数的实际结果是正确的(也就是说,是测试的预期结果):

    is_prime?(2) == true: true
    is_prime?(3) == true: true
    is_prime?(4) == false: true
    is_prime?(9) == false: true
                      ^      ^
                      |      |
                      |      true if the test passed; false if failed
                      |
                      What the function should have returned
    

    如果最右边的列包含所有“真”值,则该函数已通过所有测试。

    【讨论】:

      猜你喜欢
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 2014-01-21
      • 2018-04-21
      • 2021-10-29
      • 2013-03-11
      相关资源
      最近更新 更多