What does "self" mean in Ruby?
Experiments with self
Assumptions
-
Perhaps you have heard of ‘object / receiver / sender’ terminology. If not, please consider this tutorial post
-
It is assumed you know what a
class
means, and perhaps what an “instance method” is.
What is self
?
It is not uncommon to see self
bandied around in Ruby. What does it mean?
Asking this is analogous to asking: “who is winning” when watching a sporting contest: the answer depends on the context. Similarly, self
can be different things, based on the context.
Student Exercise
I would encourage you to copy and paste the following in a ruby file, and to complete the exercise for yourself:
puts "what is self right now? It is #{self} - we are guessing: ....insert_your_answer_here"
class Car
puts "what is self right now? It is #{self} - we are guessing: ....insert_your_answer_here"
class << self
puts "what is self right now? It is #{self} - we are guessing: ....insert_your_answer_here"
puts "Are we in the eigenclass? #{self == Car.singleton_class}"
def speed
puts "what is self right now? - we are guessing: ....insert_your_answer_here"
end
end
def start
puts "what is self right now? It is #{self} - we are guessing: ....insert_your_answer_here"
end
end
ferrari = Car.new
ferrari.start
Car.speed
The Answers
Consider the following:
puts "what is self right now? It is #{self} - we are guessing main "
class Car
puts "what is self right now? It is #{self} - we are guessing 'Car'"
class << self
puts "what is self right now? It is #{self} - we are guessing 'eigenclass'"
puts "Are we in the eigenclass? #{self == Car.singleton_class}"
def speed
puts "In speed: what is self right now? It is #{self} - we are guessing Car"
end
end
def start
puts "what is self right now? It is #{self} - we are guessing: an instance of car"
end
end
ferrari = Car.new
ferrari.start
Car.speed
## The output
#=> what is self right now? It is main - we are guessing main
#=> what is self right now? It is Car - we are guessing 'Car'
#=> what is self right now? It is #<Class:Car> - we are guessing 'eigenclass'
#=> Are we in the 'eigenclass? true
#=> what is self right now? It is #<Car:0x0000561c55362de8> - we are guessing: an instance of car
#=> in speed - what is self right now? - we are guessing Car
Implicit Receiver
You may have heard the expression: everything is an object, in ruby. If that is the case, when we call a method - what if there is no object? In this case, the object is “implicit”: in other words, the implicit receiver is self
.
def test
puts "what is the receiver here?"
end
test
# => what is the receiver here?
# the receiver is self, which in this case is the main object