tags:

views:

116

answers:

1

I am struggling to understand how singleton methods work in Ruby at the object level. When I define a simple Person class and add singleton method and instance methods and try to access eigenclass object id of that object it returns different ids. To put simply here 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's object id #{self.object_id}" #Line 35 - 22609820
  end
end

Now I add method prsn1_specific_method to Person object instance's singleton class and access its object id from there(Line 8). Then in instance method method1 I access the same eigen class(Line 35) if I am correct. (Line numbers may not be correct so I have commented them out for clarity.) Why two different object ids if they are part of the same singleton class created for that prsn1 object.

And also for Person class's Line 19 object id and Line 23 object ids are also different if they are part of same singleton class created for Person class. Am I doing something wrong with object id access ?? Please if someone can give me a better explanation on how Class objects are being associated when an singleton method is created for a particular object.

One more thing is, without using require 'singleton' and including singleton as module, I need to make a custom method that I have added to (say Array class) available as only one method even if I create hundreds of array objects.

Thanks

+3  A: 

The self in prsn1_specific_method is not the eigenclass. You're defining an instance method on the eigenclass, and what is self in an instance method? The instance! Therefore, self there refers to the object prsn1.

Chuck