Self - The current/default object

At every point when your program is running, there is one and only one self - the current or default object accessible to you in your program. You can tell which object self represents by following a small set of rules.

Top level context

The top level context is before you have entered any other context, such as a class definition. Therefore the term top level refers to program code written outside of a class or module. If you open a new text file and type:

you have created a top level local variable x. If you type:

you have created a top level method - an instance method of Object (even though self is not Object). Top-level methods are always private. Ruby provides you with a start-up self at the top level. If you type:

it displays main - a special term the default self object uses to refer to itself. The class of the main object is Object.

Self inside class and module definitions

In a class or module definition, self is the class or module object.

The output is:

Self in instance method definitions

At the time the method definition is executed, the most you can say is that self inside this method will be some future object that has access to this method.

The output is:

The output #<S:0x2835908> is Ruby's way of saying "an instance of S".

Self in singleton-method and class-method definitions

Singleton methods - those attached to a particular object can be called by only one object. When a singleton method is executed, self is the object that owns the method, as shown below:

The output of the above example is:

Class methods are defined as singleton methods for class objects. Refer to the following program:

The output is:

self inside a singleton method (a class method, in this case) is the object whose singleton method it is.

Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on rubylearning.github.io and in the course at rubylearning.org is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.