我想弄清楚为什么这样做有效,以及这是否是一种不好的做法。
以下代码将抛出一个SyntaxError:
if true &&
puts "ok"
end
虽然下面的代码不会,但它会按预期执行:
if true &&
if true
puts "ok"
end
end
我在编写一个包含大量条件链的 if 语句的 ruby 脚本时遇到了这个问题,所以我将每个条件放在单独的行中,然后注释掉最后一个并执行脚本。此刻,我意识到 if 语句以 && 运算符结尾。虽然我预计它会抛出异常,但令我惊讶的是它并没有抛出异常,因为紧随其后的是另一个 if 语句。
我的 ruby 版本是 ruby 2.2.6p396(2016-11-15 修订版 56800)[x86_64-darwin16]
。
最佳答案
I'm trying to figure out why this works and whether it's a bad practice.
后一个问题很难回答,因为你的代码太抽象了。此外,“不良做法”是基于意见的,因此是题外话。
The following code will throw a SyntaxError:
if true && puts "ok" end
这是一条红鲱鱼。请阅读错误信息:
SyntaxError: unexpected string literal, expecting `do' or '{' or '('
puts "ok"
^
它没有说明 if
的任何内容。
我希望你的代码等同于
if true && puts "ok"
end
这确实引发了相同的 SyntaxError
:
SyntaxError: unexpected string literal, expecting `do' or '{' or '('
if true && puts "ok"
^
我们可以进一步缩小到
true && puts "ok"
这是因为 &&
比以空格分隔的参数列表具有更高的优先级,因此这一行被解析为
(true && puts) "ok"
因此,为了消除歧义,我们需要在参数列表中添加括号:
if true &&
puts("ok")
end
现在代码按预期工作。
Though the following code will not, it will execute as expected:
if true && if true puts "ok" end end
的确,这是完全合法的。行尾的二元运算符将隐式地继续该行,即此代码等效于:
if true && if true
puts "ok"
end
end
或
if true && if true then puts "ok" end
end
或
if true && if true then puts "ok" end then end
I came across this while writing a ruby script with an if statement
这就是您困惑的根源:这不是 if
语句。这是一个 if
表达式。 (从技术上讲,ISO Ruby 语言规范将其称为条件表达式。)Ruby 中没有语句,只有表达式。
I was amazed that it didn't because another if statement followed right after.
它不是一个声明。它是一个与任何其他表达式一样的表达式。 foo && bar
是完全合法的,foo && if true then 23 end
也是完全合法的因为它们是完全一样的东西:一个&&
运算符,两边都有一个表达式。
关于ruby - 是否有一个 if 语句后跟另一个以在 ruby 中以 'and' 运算符 (&&) 结束该行的原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57729290/