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

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

    The logical or operator || works on boolean expressions, so using it on strings doesn't do what you want.

    There are several ways to achieve what you want that are less verbose and more readable.

    Using Array#include? and a simple if-statement:

    if ["projects", "parts"].include? @controller.controller_name
      do_something
    else
      do_something_else
    end
    

    Using a case-statement:

    case @controller.controller_name
    when "projects", "parts" then
      do_something
    else
      do_something_else
    end
    

提交回复
热议问题