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
    self
  end
end

g = Ghost.new
g.reflect == g # => true

Inside a class or module method:

class Ghost
  def self.reflect
    self
  end
end

Ghost.reflect == Ghost # => true

Inside a class or module definition:

class Ghost
  self == Ghost # => true
end 

module Mummy
  self == Mummy # => true
end 

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.
Advertisements
self in Ruby

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