self in Ruby

self is a special variable that points to the object that “owns” the currently executing code.

self is the “current object” and the default receiver of messages (method calls) for which no explicit receiver is specified. (Which object plays the role of self depends on which context).

Inside an instance method:

class Ghost
  def reflect

g =
g.reflect == g # => true

Inside a class or module method:

class Ghost
  def self.reflect

Ghost.reflect == Ghost # => true

Inside a class or module definition:

class Ghost
  self == Ghost # => true

module Mummy
  self == Mummy # => true

Source: [www]

The Golden Three Rules of Self

  1. Use self when setting/getting instance attributes inside a class definition.
  2. Use self to denote a method within the class definition as a class method.
  3. Use self to reference the calling object within an instance method definition.
self in Ruby

One thought on “self in Ruby

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s