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

后端 未结 9 1527
再見小時候
再見小時候 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条回答
  •  情话喂你
    2020-11-28 07:57

    || is also a null coalescing operator, so

    "projects" || "parts"
    

    will return the first string that is not null (in this case "projects"), meaning that in the second two examples, you'll always be evaluating:

    if @controller.controller_name == "projects"
    

    Firing up irb, you can check that this is happening:

    a = "projects"
    b = "parts"
    
    a || b
    

    returns projects

提交回复
热议问题