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
self
end
end
we have sir biboo a polite alien.
biboo = Alien.new
biboo.reflect == biboo
so Mr biboo will see himself in the mirror!
self in class method
class Alien
def self.reflect
self
end
end
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 ( https://dev.to/samuelfaure/explaining-ruby-s-singleton-class-eigenclass-to-confused-beginners-cep ) that blew my mind!
#We can create ExampleObject like this :
class ExampleObject
end
# Or like this :
ExampleObject = Class.new
ExampleObject.new.class # => ExampleObject
ExampleObject.class # => Class
Class.class # => Class
ExampleObject.class.class.class.class # => Class
According to the Example:
our Alien will say Hi in another language
class ExampleAlien
def printHello
puts 'Hello'
end
end
Alien1 = ExampleAlien.new
Alien2 = ExampleAlien.new
class << Alien2
def printHello
puts 'Aloha'
end
end
Alien1.printHello # => 'Hello'
Alien2.printHello # => 'Aloha'
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)