Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the "||" OR operator in If conditionals in Ruby

Just briefly, why are the following three lines not identical in their impact?

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

The first gives me the result I want, but as there's actually more options than just projects and parts, using that form creates a verbose statement. The other two are more compact, but don't give me the same result.

like image 889
steven_noble Avatar asked Oct 12 '09 12:10

steven_noble


People also ask

What does || in Ruby mean?

a ||= b is a conditional assignment operator. It means: if a is undefined or falsey, then evaluate b and set a to the result. Otherwise (if a is defined and evaluates to truthy), then b is not evaluated, and no assignment takes place.

What is || in if condition?

Thus, || computes the same result as | on boolean or Boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

What does || operator in Ruby?

The || operator returns the Boolean OR of its operands. It returns a true value if either of its operands is a true value. If both operands are false values, then it returns a false value. Like && , the || operator ignores its righthand operand if its value has no impact on the value of the operation.

Can you use || in an if statement?

In the logical OR ( || ) operator, if one or both of the conditions are true , then the code inside the if statement will execute.


2 Answers

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 
like image 115
Martin DeMello Avatar answered Sep 30 '22 19:09

Martin DeMello


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.

like image 29
Jim Avatar answered Sep 30 '22 20:09

Jim