理解“||"Ruby 中 If 条件中的 OR 运算符 [英] Understanding the "||" OR operator in If conditionals in Ruby
问题描述
简单地说,为什么以下三行的影响不同?
Just briefly, why are the following three lines not identical in their impact?
if @controller.controller_name == "projects" || @controller.controller_name == "parts"
if @controller.controller_name == ("projects" || "parts")
if @controller.controller_name == "projects" || "parts"
第一个给出了我想要的结果,但实际上除了项目和零件之外还有更多的选择,使用这种形式会创建一个冗长的语句.其他两个更紧凑,但不要给我相同的结果.
The first gives me the result I want, but as there's actually more options than just projects and parts, using that form creates a verbose statement. The other two are more compact, but don't give me the same result.
推荐答案
|| 的确切语义是:
the exact semantics of || are:
- 如果第一个表达式不是 nil 或 false,则返回它
- 如果第一个表达式为 nil 或 false,则返回第二个表达式
所以你的第一个表达式的结果是,如果 @controller.controller_name == "projects"
,那么表达式短路并返回 true
.如果没有,它会检查第二个表达式.第二个和第三个变体本质上是 if @controller.controller_name == "projects"
,因为 "projects" ||"parts"
等于 "projects"
.你可以在 irb 中试试这个:
so what your first expression works out to is, if @controller.controller_name == "projects"
, then the expression short-circuits and returns true
. if not, it checks the second expression. the second and third variants are essentially if @controller.controller_name == "projects"
, since "projects" || "parts"
equals "projects"
. you can try this in irb:
>> "projects" || "parts"
=> "projects"
你想做的是
if ["projects", "parts"].include? @controller.controller_name
这篇关于理解“||"Ruby 中 If 条件中的 OR 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!