This content has been automatically translated from Ukrainian.
Ruby has two logical "and" operators - && and and. At first glance, they are similar, but have different execution priority.
&& it has high priority, so it is usually used for logical expressions, conditions and loops.
and has low priority, so it is often used for control flow when several actions need to be performed sequentially.
Example with &&:
result = true && false # first computes true && false => false # result => false
Example with and:
result = true and false # Ruby reads as (result = true) and false # initially assign result = true # then runs logical and false, but this does not change the result variable result # => true
When and what to use?
- Use && for logic and conditions.
- Use and to perform actions (control flow) sequentially, for example return true and log_success. But it is better not to do this either. Because you can get a little confused.
Priority determines the order of the calculation, not the result of the logical operation itself.
This post doesn't have any additions from the author yet.