Understanding the “||” OR operator in If conditionals in Ruby

后端 未结 9 1503
再見小時候
再見小時候 2020-11-28 07:40

Just briefly, why are the following three lines not identical in their impact?

if @controller.controller_name == \"projects\" || @controller.controller_name          


        
9条回答
  •  Happy的楠姐
    2020-11-28 08:09

    the exact semantics of || are:

    • if first expression is not nil or false, return it
    • if first expression is nil or false, return the second expression

    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"
    

    what you want to do is

    if ["projects", "parts"].include? @controller.controller_name
    

提交回复
热议问题