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

后端 未结 9 1508
再見小時候
再見小時候 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:53

    Basically, == doesn't distribute over other operators. The reason 3 * (2+1) is the same as 3 * 2 + 3 * 1 is that multiplication distributes over addition.

    The value of a || expression will be one of its arguments. Thus the 2nd statement is equivalent to:

    if @controller.controller_name == "projects"
    

    || is of lower precedence than ==, so the 3rd statement is equivalent to:

    if (@controller.controller_name == "projects") || "ports"
    

提交回复
热议问题