The following operators are available in Ruby for testing expressions that may yield true or false values.
Operator | Description |
---|---|
and && | evaluate the left-hand side; only if the result is true do they then evaluate the right side. and has lower precedence than &&. |
or || | evaluate the left-hand side; if the result is false, then they evaluate the right side. or has lower precedence than ||. |
not ! | negate a Boolean value; they return true when false and return false when true. |
Because of the difference in precedence, conditions will be evaluated in different orders and may yield different results.
# Example 1 if ( 1==3 ) and (2==1) || (3==3) then puts('true') else # w ww. ja v a 2 s. com puts('false') end # Example 2 if ( 1==3 ) and (2==1) or (3==3) then puts('true') else puts('false') end
In fact, Example 1 prints "false," while Example 2 prints "true."
This is because or has lower precedence than ||.
Here, I have rewritten Examples 1 and 2; in each case, the addition of one pair of parentheses has inverted the initial Boolean value returned by the test:
# Example 1 (b) - now returns true if (( 1==3 ) and (2==1)) || (3==3) then puts('true') else # www .j a v a 2 s .com puts('false') end # Example 2 (b) - now returns false if ( 1==3 ) and ((2==1) or (3==3)) then puts('true') else puts('false') end