理解“||”在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.
推荐答案
||的确切语义是:
- 如果第一个表达式不是nil或false,则返回
- 如果第一个表达式是nil或false,返回第二个表达式
所以你的第一个表达式是,如果 @controller .controller_name ==projects
,然后表达式短路并返回 true
。如果没有,它会检查第二个表达式。第二个和第三个变体基本上是,如果@ 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屋!