When Does self Change?

In this chapter, you will learn that the value of self changes whenever Ruby encounters the class, module or def keyword.

Self at Top Level

Open your code editor and print the value of self.

p self

This prints:

main

Self Inside a Class

Define a class and print the value of self.

class A
  p self
end

This prints:

A

Self Inside a Module

Define a module and print the value of self.

module B
  p self
end

This prints:

B

The value of Self

Self Inside a Method in a Class

Define a method inside the class A and print the value of self.

class A
  def m
    p self
  end
end

This prints nothing. Until now Ruby executed code as it read the code. In this case, it does not execute the method as it reads it. It makes the method available for instances of class A to call it. Let's create an instance of A to call the method m().

class A
  def m
    p self
  end
end

a = A.new
a.m

This prints the instance of A:

#<A:0x007fec6b827210>

The self inside a method

Self Inside a Method in a Module

Define a method in module B and print the value of self inside the method.

module B
  def mw
    p self
  end
end

This prints nothing. We can mixin the module B in a class. Create an instance of that class and call the method mw().

module B
  def mw
    p self
  end
end

class Tester
  include B
end

t = Tester.new
t.mw

This prints:

#<Tester:0x007fdf3c805ef8>

The value of self inside the method defined in a module is the instance of Tester class.

The value of self inside a module

Self When Extending a Module

We can extend the module and call the class method mw().

module B
  def mw
    p self
  end
end

class Tester
  extend B
end

Tester.mw

This prints:

Tester

Self Inside a Module Method

Define a class method in a module to print the value of self.

module B
  def self.mw
    p self
  end
end

B.mw

This prints:

B

The self in Class Method of a Module

Self Inside a Class Method

Define a class method in a class to print the value of self.

class A
  def self.m
    p self
  end
end

A.m

This prints:

A

The self in Class Method

Summary

The following list summarizes what you learned in this chapter.

Self Location Self Value
Top Level main
Inside a Class Class name
Inside a Module Module name
Inside a Method in a Class Instance of the class
Inside a Method in a Module Instance of the class that mixes in the module
Inside a Method in a Module Class name that extends the module
Inside a class Method in a Module Module name
Inside a class Method in a Class Class name

results matching ""

    No results matching ""