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

后端 未结 9 1397
再見小時候
再見小時候 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 08:09

    There's a few different things going on there:

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

    this gives the behaviour you want I'm assuming. The logic is pretty basic: return true if the controler name is either "projects" or "parts"

    Another way of doing this is:

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

    That will check if the controller name is somewhere in the list.

    Now for the other examples:

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

    This won't do what you want. It will evaluate ("projects" || "parts") first (which will result in "projects"), and will then only check if the controller name is equal to that.

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

    This one gets even wackier. This will always result in true. It will first check if the controller name is equal to "projects". If so, the statement evaluates to true. If not, it evaluates "parts" on it's own: which also evaluates to "true" in ruby (any non nil object is considered "true" for the purposes of boolean logic")

    0 讨论(0)
  • 2020-11-28 08:11

    I see a lot of people preferring the include? comparison.

    I prefer to use the .in? operator. It is much more succinct. And also more readable, since we don't ask questions to the array, we ask questions to the variable you want to ask: On your case, the controller name.

    @controller.controller_name.in? ["projects", "parts"]
    

    Or, even better

    @controller.controller_name.in? %w[projects parts]
    
    0 讨论(0)
  • 2020-11-28 08:13

    First one compares "projects" and "parts" string literals to @controller.controller_name variable.

    Second one evaluates ("projects" || "parts") which is "projects" because "projects" string literal neither false or nil or empty string and compare it to @controller.controller_name

    Third one compares @controller.controller_name and "projects" and if they are equal, it return true, if they aren't it return "parts" which is equal to true for if statement.

    0 讨论(0)
提交回复
热议问题