Booleans and Nil

Contents

Booleans and Nil#

Booleans#

true and false are pre-definded objects in Ruby. They are the singleton objects of TrueClassand FalseClass. true and false are used as the return value of a Boolean expressions constructed with operators || (logical OR), && (logical AND) and ! (logical NOT), or a value of comparision methods or operators like == > >=

Singleton is an object which instance could be create only once. true and false are created by Ruby and exists always while running the program. Because they are singletons, every keyword true in the whole program means the same physical object in the memory. You can check it by launching true.object_id

true || false        # true OR false
#=> true
true && false        # true AND false
#=> false
!true                # NOT true
#=> false
2 > 1.0
#=> true
3 == 3
#=> true
2 > 1.0 && 3 == 3    # first to evaluate comparitions (> and ==),
#=> true                 # and then do a logical AND with results of comparitions

Nil#

nil is a way to describe nothing. In Ruby, nil is an object like everything. It is a singleton instance of NilClass. It is commonly used to return the information that something does not exists, or can not be found. For example, searching for the files on the filesytem may return the list of the file or nil in case when no files were found.

In a Boolean expression, nil behaves the same as false:

!nil           # NOT nil is true
#=> true
nil && true    # nil AND true is nil
#=> nil
nil && false   # nil AND false is nil
#=> nil
nil || true    # nil OR true is true
#=> true
nil || false   # nil OR false is false
#=> false

There is a method called nil? to check if the object is the nil. Obviously only nil returns true from this method:

nil.nil?     # nil is nil
#=> true
0.nil?       # zero is not nil
#=> false
false.nil?   # and false is not nil as well
#=> false

Such behaviour is very important in Ruby world. In all the conditional expressions (if-than-else, while, select-case) everything evaluates to true, except false and nil. Unlike in the other languages, zero, empty string, empty array evaluates to true.