Ruby - Operator Boolean Operators

Introduction

The following operators are available in Ruby for testing expressions that may yield true or false values.

OperatorDescription
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.

Demo

# Example 1 
if ( 1==3 ) and (2==1) || (3==3) then  
   puts('true')  
else  # from   www .  j  a  v a2s  .  c  o m
   puts('false')  
end 

# Example 2 
if ( 1==3 ) and (2==1) or (3==3) then  
   puts('true')  
else  
   puts('false')  
end

Result

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:

Demo

# Example 1 (b) - now returns true 
if (( 1==3 ) and (2==1)) || (3==3) then  
   puts('true')  
else  #   ww  w .j  a va  2  s .c om
   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

Result

Related Topics