Understanding Ruby Logical Operators

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Ruby Math Functions and MethodsRuby Object Oriented Programming


Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99


Introduction

The objective of this chapter is to provide an overview of Ruby Logical Operators

Ruby Logical Operators

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.

rather than to look at a code example right away, the first step to understanding how logical operators work in Ruby is to construct a sentence. 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.


Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99



PreviousTable of ContentsNext
Ruby Math Functions and MethodsRuby Object Oriented Programming