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.
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
Ruby Shell > 6.class
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
puts “I am a number.”
This can now be ran on the Class called Integer itself with the following line:
I am a number.
or for a string:
puts “I am a string.”
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.
which will output
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.