Self & Metaclasses in Ruby

Self has confused me for a while now so I decided to get to the bottom of the purpose and meaning of self.

TLDR:

  • At any point in your program, there is one and only one self
  • Self is the current object accesible to you
  • It can also be said that Self is the receiver object of the current method (ex: String is the object in String.send(:”length”))
  • Since objects in Ruby are usually instances of classes, self is usually the class you are in at any moment
  • Using self enables you to call a method on a class (like Person), instead of just one instance of a class (like Laura)
  • There are a couple different ways to call methods on self: ‘self.some_method’ OR ‘class << self’ before a group of methods
  • You might want to use self if you want to call a method on any potential¬†instance of that object (every Person is born on planet earth but not every Person is named Laura), especially if you don’t plan on having more than one instance of an object (maybe you’re creating a game with one Person, one Fish, and one Monkey–I’m not sure why you would do that–and you don’t want to create multiple instances of Person).

Okay, now for the longer explanation. Continue reading