我很努力地理解單例方法在對象級別如何在Ruby中工作。當我定義一個簡單的Person類並添加單例方法和實例方法並嘗試訪問該對象的特徵類對象ID時,它將返回不同的id。簡單來說就是我的測試代碼。在理解單例方法如何在Ruby中工作的問題
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
現在我添加方法prsn1_specific_method到Person對象實例的單例類,並從那裏訪問的對象ID(8號線)。然後在實例方法方法1我訪問相同的特徵類(第35行),如果我是正確的。 (行號可能不正確,所以爲了清晰起見,我已經對它們進行了註釋。)爲什麼兩個不同的對象標識符(如果它們是爲該對象創建的同一單例類的一部分)?
而且對於Person類的Line 19對象id和Line 23對象id,如果它們是爲Person類創建的相同單例類的一部分,它們也是不同的。我做對象id訪問錯誤?如果有人可以給我一個關於如何爲特定對象創建單例方法時關聯Class對象的更好解釋。如果不使用require'singleton'並且包含singleton作爲模塊,我需要創建一個自定義方法,我已經添加了(比如說Array類),只有一個方法可用,即使我創建了數百個數組也是如此對象。
感謝