【问题标题】:Ruby: why does `puts true and false` return true? [duplicate]Ruby:为什么`puts true and false`返回true? [复制]
【发布时间】:2019-02-08 15:54:51
【问题描述】:

在 Ruby 中,我刚刚注意到:

  • puts true and false 返回 true,而
  • puts (true and false)puts false and true 都返回 false

这种行为背后的逻辑/原因是什么?

【问题讨论】:

  • 可能是因为puts 不是关键字 - 它是一个返回 nil 的方法吗?因为true and false 在没有 puts 的情况下给出 nil。 ruby-doc.org/core-2.5.1/Kernel.html#method-i-puts
  • 从技术上讲,我会说它返回nil,而不是truefalse,并输出true。例如如果您执行语句result = (puts true and false)result 将为零。这是因为puts 返回nilnil and false 计算结果为 nil
  • 第一个不返回true,它打印true。第二个例子不返回false,它们打印`false。您将返回值与打印值混淆了。
  • @sawa:确实,你是对的。让我感到困惑的是,我使用了一个不输出返回值的在线 IDE……

标签: ruby boolean boolean-logic


【解决方案1】:

因为puts的绑定比and强:你的代码等于

(puts true) and false
true
#=> nil

您可以查看运营商precedence in docs

要获得你可以使用的&&,它的优先级高于and

puts true && false
false
#=> nil

【讨论】:

    猜你喜欢
    • 2021-11-10
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    相关资源
    最近更新 更多