题
Ruby 中的单例类本身就是一个类吗?这是所有对象都属于“类”的原因?这个概念是 模糊, ,但我相信这与我为什么可以定义类方法有关(class foo; def foo.bar ...
).
Ruby 中的单例类是什么?
解决方案
首先,稍微定义一下:A 单例方法 是仅为单个对象定义的方法。例子:
irb(main):001:0> class Foo; def method1; puts 1; end; end
=> nil
irb(main):002:0> foo = Foo.new
=> #<Foo:0xb79fa724>
irb(main):003:0> def foo.method2; puts 2; end
=> nil
irb(main):004:0> foo.method1
1
=> nil
irb(main):005:0> foo.method2
2
=> nil
irb(main):006:0> other_foo = Foo.new
=> #<Foo:0xb79f0ef4>
irb(main):007:0> other_foo.method1
1
=> nil
irb(main):008:0> other_foo.method2
NoMethodError: undefined method `method2' for #<Foo:0xb79f0ef4>
from (irb):8
实例方法是类的方法(即在类的定义中定义)。类方法是单例方法 Class
类的实例——它们没有在类的定义中定义。相反,它们是定义在 单例类 的对象。
irb(main):009:0> Foo.method_defined? :method1
=> true
irb(main):010:0> Foo.method_defined? :method2
=> false
您可以使用以下语法打开对象的单例类 class << obj
. 。在这里,我们看到这个单例类是定义单例方法的地方:
irb(main):012:0> singleton_class = ( class << foo; self; end )
=> #<Class:#<Foo:0xb79fa724>>
irb(main):013:0> singleton_class.method_defined? :method1
=> true
irb(main):014:0> singleton_class.method_defined? :method2
=> true
irb(main):015:0> other_singleton_class = ( class << other_foo; self; end )
=> #<Class:#<Foo:0xb79f0ef4>>
irb(main):016:0> other_singleton_class.method_defined? :method1
=> true
irb(main):017:0> other_singleton_class.method_defined? :method2
=> false
因此,向对象添加单例方法的另一种方法是使用对象的单例类 open 来定义它们:
irb(main):018:0> class << foo; def method3; puts 3; end; end
=> nil
irb(main):019:0> foo.method3
3
=> nil
irb(main):022:0> Foo.method_defined? :method3
=> false
总之:
- 方法必须始终属于一个类(或者:是某个类的实例方法)
- 普通方法属于它们定义的类(即是类的实例方法)
- 类方法只是 a 的单例方法
Class
- 对象的单例方法不是该对象的类的实例方法;相反,它们是对象的单例类的实例方法。
其他提示
Ruby提供了一种定义特定于特定对象的方法的方法,这种方法称为单例方法。当一个人在一个对象上声明一个单例方法时,Ruby会自动创建一个只保存单例方法的类。新创建的类称为Singleton Class。
foo = Array.new
def foo.size
"Hello World!"
end
foo.size # => "Hello World!"
foo.class # => Array
#Create another instance of Array Class and call size method on it
bar = Array.new
bar.size # => 0
Singleton类是特定于对象的匿名类,它自动创建并插入到继承层次结构中。 可以在对象上调用
singleton_methods
来获取对象上所有单例方法的名称列表。
foo.singleton_methods # => [:size]
bar.singleton_methods # => []
这篇文章真的帮助我理解Ruby中的Singleton类,它有一个很好的代码例。
正如刚刚更新@Pistos答案一样,从版本1.9.2 ruby添加新语法来获取单例类
singleton_class = ( class << foo; self; end )
可以替换为:
singleton_class = foo.singleton_class
最实用/最有效的方式(IMHO)是:作为继承链或方法查找/解析顺序。这张照片可能会有所帮助
http:// www.klankboomklang.com/2007/11/25/modules-part-i-enter-the-include-class/
这是r 1.9,对比内置和用户定义的类:我还在消化这个类。
http://d.hatena.ne.jp/sumim/20080111/p1
另外,我认为这个术语的混淆使用是<!>“; Singleton object <!>”,这是不同的概念。单例对象来自一个类,它重写了构造函数/实例化方法,因此您只能分配该类中的一个。