ruby 中的单例类到底是什么? [英] What exactly is the singleton class in ruby?
问题描述
Ruby 中的单例类本身就是一个类吗?这是所有对象都属于类"的原因吗?这个概念模糊,但我相信这与我为什么可以定义一个类方法有关(class foo; def foo.bar ...
).
Is the singleton class in Ruby a class in and of itself? Is it the reason why all objects belong to "class?" The concept is fuzzy, but I believe it has something to do with why I can define a class method at all (class foo; def foo.bar ...
).
Ruby 中的单例类是什么?
What is the singleton class in Ruby?
推荐答案
首先,稍微定义一下:单例方法是只为单个对象定义的方法.示例:
First, a little definition: a singleton method is a method that is defined only for a single object. Example:
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
实例上的单例方法——它们没有在类的定义中定义.相反,它们是在对象的单例类上定义的.
Instance methods are methods of a class (i.e. defined in the class's definition). Class methods are singleton methods on the Class
instance of a class -- they are not defined in the class's definition. Instead, they are defined on the singleton class of the object.
irb(main):009:0> Foo.method_defined? :method1
=> true
irb(main):010:0> Foo.method_defined? :method2
=> false
您使用语法 class << 打开对象的单例类.对象
.在这里,我们看到这个单例类是定义单例方法的地方:
You open the singleton class of an object with the syntax class << obj
. Here, we see that this singleton class is where the singleton methods are defined:
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
因此,向对象添加单例方法的另一种方法是在对象的单例类打开的情况下定义它们:
So an alternative means of adding singleton methods to an object would be to define them with the object's singleton class 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
总结:
- 方法必须始终属于一个类(或:是某个类的实例方法)
- 普通方法属于定义它们的类(即类的实例方法)
- 类方法只是
Class
的单例方法 - 对象的单一方法不是对象类的实例方法;相反,它们是对象的单例类的实例方法.
这篇关于ruby 中的单例类到底是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!