Understanding Ruby Logical Operators

Revision as of 19:17, 19 November 2007 by Neil (Talk | contribs)

Revision as of 19:17, 19 November 2007 by Neil (Talk | contribs)

Logical Operators are also known as Boolean Operators because they evaluate parts of an expression and return a true or false value, allowing decisions to be made about how a script should proceed.

The first step to understanding how logical operators work in Ruby is to construct a sentence rather than to look at a script example right away. Let's assume we need to check some aspect of two variables named var1 and var2. Our sentence might read:

If var is less than 25 AND var2 is greater than 45 then return true

Here the logical operator is the "AND" part of the sentence. If we were to express this in Ruby we would use the comparison operators we covered earlier together with the and or && logical operators:

var1 = 20
var2 = 60
var1 < 25 and var2 > 45
=> true

Similarly, if our sentence was to read:

If var1 is less than 25 OR var2 is greater than 45 return true.

Then we would replace the "OR" with the Ruby equivalent or, or '||':


var1 < 25 or var2 > 45
=> true

Another usefulLogical Operator is the not operator which simply inverts the result of an expression. The ! character represents the NOT operator and can be used as follows:

10 == 10        # returns ''true''
=> true

!(10 == 10)       // returns ''false'' because we have inverted the result with the not operator
=> false

Logical operators are of particular use when constructing conditional code, a topic which will be covered in details in Ruby Flow Control.