【问题标题】:Why does Ruby 1.9.2 give a syntax error for: puts(true and false)?为什么 Ruby 1.9.2 会给出一个语法错误:puts(true and false)?
【发布时间】:2012-03-08 19:45:54
【问题描述】:

我很困惑 Ruby 1.9(JRuby 1.6.6 (RUBY_VERSION == "1.9.2") 和 Ruby 1.9.3-p125)给出了puts(true and false) 的语法错误。

我不知道为什么 - 这里有什么问题?我将如何正确编写那段代码? puts(true && false) 有效,但有 and 的解决方案吗?

irb 会话示例:

1.9.3p125 :001 > puts(true and false)
SyntaxError: (irb):1: syntax error, unexpected keyword_and, expecting ')'
puts(true and false)
             ^
    from /home/fr/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'
1.9.3p125 :002 > puts(true && false)
false
 => nil 

感谢 Mladen Jabnović 简化了示例。旧示例是f(true and f(false))

【问题讨论】:

  • 简化的例子是puts(true and false)
  • 感谢@Thilo 和@Mladen。我知道运算符优先级,但对我来说这并不能解释这种现象。感谢puts 的示例,这要简单得多。

标签: ruby


【解决方案1】:

这都是关于优先级 “and”和“&&”在操作数上没有相同的优先级,尝试使用

f((true and f(false)))

'and' 应该用于诸如“如果一切正常,则执行 A,然后执行 B”之类的内容,而不是用于严格的布尔检查。

check_db(param) and connect_db(param)

【讨论】:

    【解决方案2】:

    ruby 中的operator precedence= 之前是&amp;&amp;,在and 之前。因此,在您使用and 的示例中,它会尝试进行此(隐式)分配:

    puts(true 
    

    然后结合

    false)
    

    通过and,这会导致语法错误。在这里查看一个很好的解释:Difference between "and" and && in Ruby?

    编辑:我不确定我的“隐式分配”是否有意义 - 考虑一下这个声明以使其明确:

    foo = puts(true and false)
    

    编辑 2:请记住,方法调用实际上是在对象上调用的。所以这两种情况的等效语句是:

    Object.send("puts", true && false) # this works
    Object.send("puts", true and false) # this is a syntax error
    Object.send("puts", (true and false)) # works again
    

    不确定这是否有帮助 - 你是对的,这有点违反直觉。我的解决方案是远离and :)

    【讨论】:

    • 这对我来说太违反直觉了。这意味着and 的优先级低于方法参数括号。这只是 Ruby 中的一个错误,还是背后有一个我还不明白的概念?
    猜你喜欢
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 2021-08-08
    • 2018-06-17
    相关资源
    最近更新 更多