DEV Community

Cover image for "Sophie's World in Ruby"
Kimia Kamrava
Kimia Kamrava

Posted on

"Sophie's World in Ruby"

Self in Ruby

If You are a beginner self can be a little bit confusing, so I decided to do a comic out of self. It's like the book "Sophie's World" where she wanted to understand who she is and where did she come from?
That being said let's go way back to understand self.
we know everything created by Creator Ruby is an object and this means all the codes or "storylines" "belongs" to some object. Just like in real life there will be many objects with many storylines.
when there is so much data how can we find the owner of the code or the object?
That is where Ruby Keyword comes and gives us access to the current object!


sorry to say there is not much philosophy behind it.But you will have the power to type in self and ruby knows which object you are talking about. The tricky part starts right now:

The current object depends on the context.

before we start with the examples =>

!Hint: if everything is an object even classes are objects...then we can use self when defining Classes, Methods, Modules.
In the following Examples, there will be Aliens standing in front of the mirror trying to figure out who they really are?

self in instance method

class Alien
  def reflect
Enter fullscreen mode Exit fullscreen mode

we have sir biboo a polite alien.
biboo =
biboo.reflect == biboo

so Mr biboo will see himself in the mirror!


self in class method

class Alien
  def self.reflect
Enter fullscreen mode Exit fullscreen mode

Alien.reflect == Alien

Here the Object is not Mr biboo but the class Alien, which i see as a factory object making lots of Aliens for us:D.


!Hint: A reminder that it works the same inside of modules.

Class << self

Before this Example once more we were told everything is an object in ruby world right? so the Class of any class is Class, checkout this blog ( ) that blew my mind!

#We can create ExampleObject like this :
class ExampleObject

# Or like this :
ExampleObject = # => ExampleObject
ExampleObject.class # => Class
Class.class # => Class
ExampleObject.class.class.class.class # => Class
Enter fullscreen mode Exit fullscreen mode

According to the Example:
our Alien will say Hi in another language

class ExampleAlien
  def printHello
    puts 'Hello'

Alien1 =
Alien2 =

class << Alien2
  def printHello
    puts 'Aloha'

Alien1.printHello # => 'Hello'
Alien2.printHello # => 'Aloha'
Enter fullscreen mode Exit fullscreen mode


A list of other-self uses:
•Define class-level methods
• Use an instance method when you have a local variable of the same name
• Returning Self (builder pattern)
• Debugging
• Comparing objects (==)
• Default receiver of method calls

Hope you had fun understanding self. so Who are you really?

Top comments (0)