Understanding Ruby 'self'

Posted by Andrew Schutt on November 24, 2020 · 2 mins read

Fundamentally Ruby works by invoking methods on objects. Everything in Ruby is an Object. This includes Boolean by means of TrueClass and FalseClass classes.

But what about the method puts? This common method (message) is simply called without prefixing an object (receiver).

Here we create a simple variable and assign a value followed by invoking the captialize method on the String. Then this puts thing without any object and the name variable passed in as an argument.

name = "andrew"
name.capitalize

puts name

What object is this call happening on?

Any method call most occur on an object, so, what object is is the receiver for puts? Any time a receiver is missing the default object is “self

self

  • Always references the “current object”
  • Is the default receiver for method calls
  • Changes depending on where you are
puts self # => "main"
pus self.class # => "Object"

At the top level scope of a Ruby program is an object called main that we are seeing from puts self. This object is automatically used as the receiver for the method call when no explicit receiver is specified.

puts self

is effectively the same as…

self.puts self # Note: this doesn't actually work...

Remember EVERY method is called on an object!