Pseudo Variables

In this chapter, you will learn about the pseudo-variables true, false, nil, self and super.

What are Pseudo variables?

The nil, true, false, self and super are pseudo-variables. Why are they called pseudo-variables? Because they are predefined and we cannot assign values to them.

The true, false, and nil are constants. The self and super vary dynamically as the code executes.

The boolean classes

The true and false are unique instances of the boolean classes TrueClass and FalseClass.

 > true.class
 => TrueClass 
 > false.class
 => FalseClass

The Concept of Nothing is an Object

The nil is an unique instance of NilClass.

 > nil.class
 => NilClass

The nil is a false value that represents 'no value' or 'unknown'. It expresses nothing.

> p 'false' unless false
"false"
 => "false" 

> p 'false' unless nil
"false"
 => "false"

The unless is equal to negation with if statement:

p 'false' if !nil
"false"
 => "false"

This shows that nil is a false value.

The self and super

The self always refers to the receiver of the current executing method. The super also refers to the receiver of the current method. But when you send a message to super, the method look-up changes. The method look-up starts from the super-class of the class containing the method that uses super.

class Vehicle
  def initialize(wheels)
    @wheels = wheels
  end
end

class Car < Vehicle
  attr_reader :wheels

  def initialize(color)
    super(4)
    @color = color
  end
end

car = Car.new('red')
p car.wheels

In this example, the super is in the Car class. The method look-up starts from the super-class of Car, Vehicle. This prints:

4

Assigning Values

You can see that we get an error when we assign a value to true, false or nil.

   > nil = 1
 SyntaxError: (irb):1: Can't assign to nil
 nil = 1
      ^
     from /Users/bparanj/.rvm/rubies/ruby-2.3.0/bin/irb:11:in `<main>'
  > true = 1
 SyntaxError: (irb):2: Can't assign to true
 true = 1
       ^
     from /Users/bparanj/.rvm/rubies/ruby-2.3.0/bin/irb:11:in `<main>'
  > false = 1
 SyntaxError: (irb):3: Can't assign to false
 false = 1
        ^
     from /Users/bparanj/.rvm/rubies/ruby-2.3.0/bin/irb:11:in `<main>'

You can see that we get an error when we try to change the value of self.

> self = 1
SyntaxError: (irb):7: Can't change the value of self
self = 1
      ^
    from /Users/bparanj/.rvm/rubies/ruby-2.3.0/bin/irb:11:in `<main>'

We get a syntax error when we try to change the value of super.

> super = 1
SyntaxError: (irb):12: syntax error, unexpected '='
super = 1
       ^
    from /Users/bparanj/.rvm/rubies/ruby-2.3.0/bin/irb:11:in `<main>'

Summary

In this chapter, you learned about the pseudo-variables true, false, nil, self and super. We cannot assign any values to them. The true, false and nil are predefined. The self and super varies dynamically.

results matching ""

    No results matching ""