I am currently practicing/learning singleton methods and singleton classes in Ruby, and I have come across a doubt. Given:
myobject = Object.new
Is there any difference between doing this:
def myobject.mymethod
end
and doing this:
class << myobject
def mymethod
end
end
If there is, when would we use one or the other? What are the implications?
Use ruby –dump ins to research the result, as follows:
1.
executes ruby –dump ins test.rb
the output is:
2.
executes ruby –dump ins test.rb
the output is:
So def myobject.method the way is that first sends core#define_singleton_method message to the myobject ,
then, the core#define_singleton_method message’s implementation gets the myobject’s singleton class, and add method definition into
the singleton class.
class << myobject the way is that first sends singletonclass message to the myobject , then, send core#define_method message to the myobject’s singletonclass.
In practice,
if you want to define a some of singleton methods for the obj, use class << obj.
if you only define a singleton method for the obj, use def obj.method.