Understanding the "||" OR operator in If conditionals in Ruby
Solution 1:
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
Solution 2:
The difference is the order of what's happening. Also the || isn't doing what you think it does in the 2 and 3.
You can also do
if ['projects','parts'].include?(@controller.controller_name)
to reduce code in the future if you need to add more matches.
Solution 3:
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")
Solution 4:
||
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
Solution 5:
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"