Jan 25

Meaning of ’self’ in Ruby

Category: Programming, Ruby

This came up today. When defining classes in Ruby “self” can refer to the class or the instance of that class depending on the context and understanding which is which is important.

When defining a class “self” in the context of the class definition refers to the object representing the class being defined. When in a (non-class-level) method “self” refers to the instance of the object. So:

class SomeClass
  #dynamically add a method to the SomeClass object. 
  #self is the SomeClass class object
  #now I can call SomeClass.class_level_method
  def self.class_level_method
    self == SomeClass #this is true....
  #define an instance level method
  def instance_level_method
    self #this is now an instance of the object

This syntax may make more sense in terms of the following

class SomeClass
#this can be done outside of the class definition
def SomeClass.class_level_method
  echo "hi"
c = SomeClass.new
d = SomeClass.new
#class objects are notspecial in this regard. 
#You can do the same thing to
#a specific object instance of any other type.
def c.specific_instance_method
  #this method is defined just for this 
  #specific instance of this class
c.specific_instance_method #no problem
d.specific_instance_method #nope!
Comments are off for this post

Comments are closed.