Understanding Ruby’s self method.

I as many others found the Ruby’s self method a little confusing at first, but I hope I can clear it up with the quick following explanation.

class Integer
def whatsmyself
puts self
end
end
5.whatsmyself
6.whatsmyself

Can you guess what the output of the last 2 lines are? They return ‘5’ and ‘6’ respectively.

My understanding is that the self method outputs the instance of the Class the that method is run on. We know that 5 and 6 already belong to the class called Integer, and we can demonstrate that with:

Ruby Shell > 5.class
=> Integer
Ruby Shell > 6.class
=> Integer

In these cases, the instances of the Integer class are the the instances 5 and 6. So 5 and 6 are returned.

This allow us to do an interesting thing which is define a method inside the Class instance itself, and thus run our own methods on Classes (aka Class Methods) rather than Instances of that Class (aka Instance Methods). eg

class Integer
def self.whoami
puts “I am a number.”
end
end

This can now be ran on the Class called Integer itself with the following line:

Integer.whoami

which outputs

I am a number.

or for a string:

class String
def self.whoami
puts “I am a string.”
end
end
String.whoami

which outputs

I am a string.

If we want to take it one step further we can simply run self inside of the Class itself rather than in a Class Method or Instance Method.

class Integer
puts self
end

which will output

Integer

In summary, the self is a method which is executed inside of the block of Code called Class. When this self method is not inside another Instance Method of that class, it will simply return the name of the class, which is itself. If the self method is inside of an instance method (ie a method inside of a class), then self will only be called to return the name of the method. If that method is self itself (like we did above), then it will return the classname. If that method is an Instance Method (a method defined within a class that is not the self method), then it will return whatever Instance of that class we defined (eg 5 or 6).

I hope this was helpful.