Difference between revisions of "Understanding Ruby Logical Operators"

From Techotopia
Jump to: navigation, search
Line 45: Line 45:
 
</pre>
 
</pre>
  
Logical operators are of particular use when constructing conditional code, a topic which will be covered in details in [[Ruby Flow Control]].
+
Logical operators are of particular use when constructing conditional code, a topic which will be covered in detail in [[Ruby Flow Control]].
  
  

Revision as of 12:48, 1 December 2007

PreviousTable of ContentsNext
Ruby Math Functions and MethodsRuby Object Oriented Programming


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 program should proceed.

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

If var1 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 useful Logical 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 detail in Ruby Flow Control.



PreviousTable of ContentsNext
Ruby Math Functions and MethodsRuby Object Oriented Programming