Ruby:单例类真的拥有匿名类吗?
在《编程Ruby 1.9和2.0》一书的第24.2章中,给出了以下代码:Ruby:单例类真的拥有匿名类吗?,ruby,singleton,Ruby,Singleton,在《编程Ruby 1.9和2.0》一书的第24.2章中,给出了以下代码: animal = "cat" def animal.speak puts "The #{self} says miaow" end 解释为:“当我们为“cat”对象定义singleton方法时,Ruby创建了一个新的匿名类,并在该类中定义了speak方法。这个匿名类称为singleton类(有时称为特征类)。” 不幸的是,我无法验证Ruby(2.5.1)是否确实创建了自己的匿名类: str = "a string"
animal = "cat"
def animal.speak
puts "The #{self} says miaow"
end
解释为:“当我们为“cat”对象定义singleton方法时,Ruby创建了一个新的匿名类,并在该类中定义了speak方法。这个匿名类称为singleton类(有时称为特征类)。”
不幸的是,我无法验证Ruby(2.5.1)是否确实创建了自己的匿名类:
str = "a string" # => "a string"
[str, str.object_id] # => ["a string", 47279316765840]
[str.class, str.class.object_id] # => [String, 47279301115420]
def str.greet
"hello"
end # => :greet
str.greet # => "hello"
[str, str.object_id] # => ["a string", 47279316765840]
[str.class, str.class.object_id] # => [String, 47279301115420]
如上所述,str的类在定义了singleton方法greet之后没有改变:它仍然显示为具有相同对象id 47279301115420的String
那么,匿名类在哪里
str = "a string" # => "a string"
[str, str.object_id] # => ["a string", 47279316765840]
[str.class, str.class.object_id] # => [String, 47279301115420]
def str.greet
"hello"
end # => :greet
str.greet # => "hello"
当您询问str.class
或查看ancestory链(str.class.祖先
)时,Ruby会隐藏特征类。但是,您可以在使用
当您询问str.class
或查看ancestory链(str.class.祖先
)时,Ruby会隐藏特征类。然而,您可以在使用Thx检查其类后通过返回self来获得对特征类的引用。令人惊讶的是,str_类的to_表示形式(“#class:#>”)中的十六进制字符串既不等于str_class.object_id,也不等于str.object_id。知道哪个object_id是十六进制字符串吗。令人惊讶的是,str_类的to_表示形式(“#class:#>”)中的十六进制字符串既不等于str_class.object_id,也不等于str.object_id。知道哪个object_id是十六进制字符串吗?
str_class = class << str
self
end
# => #<Class:#<String:0x007fbba28b3f20>>
str_class.instance_methods(false) #=> [:greet] # the singleton method you defined becomes the instance method of this eigenclass. :)
str_class.ancestors
[#<Class:#<String:0x007fbba28b3f20>>, String, Comparable, Object, Kernel, BasicObject]