Understanding Ruby Logical Operators

From Techotopia
Revision as of 18:52, 19 November 2007 by Neil (Talk | contribs) (New page: ''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...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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 logical operator:

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:


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