Ruby’s Main Object (Top Level Context)

Ruby creates an object called main whenever the Ruby starts and main is the top level context (aka top level scope) of the Ruby program. Methods defined in the top level scope (i.e. methods that are not wrapped in a class or module) will be bound to the main object. main is an instance of the Object class and it’s easy to play with main in IRB.

>> self # => main
>> self.class # => Object

In IRB, methods defined in the top level scope are bound to main as public instance methods.

>> def krusty; end
>> self.public_methods.include?(:krusty) # => true

IRB binds methods in the top level scope to main as public methods for convienience, but regular Ruby programs bind methods defined in the top level scope to main as private methods.

def hey_hey; end
p self # => main 
p self.private_methods.include?(:hey_hey) # => true

Everything in executed inside an object in Ruby and methods are bound to the value of self. Whenever self points to main, the methods are bound to main.

main is the message sender when methods are called in the top level context.

class Person
  def warm_blooded?
    true
  end
end

p = Person.new
puts self # => main
# p is the message receiver
# :warm_blooded? is the message
# main is the message sender
p.send(:warm_blooded?)

The message sender is the value of self, which is main in the top level context. p is the message receiver and :warm_blooded? is the message that is sent.

Instance variables defined in the top level context are also bound to the main object.

@something = 42
p self # => main
p self.instance_variables # => [:@something]

Chuck from StackOverflow provides more details about main here and describes how main sends messages here.

Advertisements

2 thoughts on “Ruby’s Main Object (Top Level Context)

  1. Pingback: Ruby’s Scope Gates | Ruby/Rails Programming

  2. Pingback: Ruby’s Binding Class (binding objects) | Ruby/Rails Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s