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.
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.
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.
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.
In the logical OR ( || ) operator, if one or both of the conditions are true , then the code inside the if statement will execute.
the exact semantics of || are:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With