The problem is understanding how single methods work in Ruby
I am struggling to understand how single methods work in Ruby at the object level. When I define a simple Person class and add a singleton method and instance methods and try to access the id of the eigenclass of that object, it returns different IDs. Simply put, this is my test code.
class Person
attr_accessor :someAccessor
def method1
puts "instance object id of Person = #{self.object_id}"
puts "Eigenclass object id of person instance object
#{(class << self; self;end).object_id}" #Line 8 - object id 22609690
end
puts "Person eigenclass object id #{(class << self; self;end).object_id}"
def self.printSingletonPersonObjectId
puts self.object_id
end
class << Person
puts "Inside Person eigenclass and its object id #{self.object_id}" #line 19 - 22609860
def uniqueForAllPeople
puts "Person eigenClass object id accessing from a Person class
class method #{self.object_id}" #Line 23 - 22609840
end
end
end
prsn1 = Person.new
class << prsn1
def prsn1_specific_method
puts "prsn1 object eigen class object id #{self.object_id}" #Line 35 - 22609820
end
end
Now I add the prsn1_specific_method method to the Singleton class instance of the Person object instance and get its object ID (line 8). Then, in the case of method1 , I can access the same class (line 35), if I'm correct. (The line numbers might be wrong, so I cleared them up for clarity.) Why are there two different object IDs if they are part of the same singleton class created for this prsn1 object .
And also for the Person ID of the Line class and the IDs of the Line 23 objects are also different if they are part of the same singleton created for the Person class. Am I doing something wrong with accessing the object? Please if someone can give me a better explanation of how class objects are related when one method is created for one object.
One more thing: without using "singleton" and including Singleton as a module, I need to create my own method that I added (for example, the Array class), available only as one method, even if I create hundreds of array objects.
thank
source to share