基于我所知道的,是的,但是我是红宝石的诺布,并且想要确定。他们的工作有什么不同吗?是否有理由使用一种语法而不是另一种语法?
我知道def self.method
和self
在类/模块的上下文之外使用会有不同的行为,因为class Foo
def m1
'm1'
end
class << self # 1
def m2
'm2'
end
end
def self.m3 # 2
'm3'
end
def Foo.m4 # 3
'm4'
end
end
Foo.singleton_methods
# => [:m2, :m3, :m4]
是不同的。
Foo.method
我见过class << self vs self.method with Ruby: what's better?,并没有谈及39 6.5.3 Singleton classes
40 Every object, including classes, can be associated with at most one singleton class. The singleton
41 class defines methods which can be invoked on that object. Those methods are singleton methods
42 of the object. If the object is not a class, the singleton methods of the object can be invoked
43 only on that object. If the object is a class, singleton methods of the class can be invoked only
44 on that class and its subclasses (see 6.5.4).
14
1 A singleton class is created, and associated with an object by a singleton class definition (see
2 13.4.2) or a singleton method definition (see 13.4.3).
3 EXAMPLE 1 In the following program, the singleton class of x is created by a singleton class definition.
4 The method show is called a singleton method of x, and can be invoked only on x.
5 x = "abc"
6 y = "def"
7
8 # The definition of the singleton class of x
9 class << x
10 def show
11 puts self # prints the receiver
12 end
13 end
14
15 x.show # prints abc
16 y.show # raises an exception
17 EXAMPLE 2 In the following program, the same singleton method show as EXAMPLE 1 is defined
18 by a singleton method definition. The singleton class of x is created implicitly by the singleton method
19 definition.
20 x = "abc"
21
22 # The definition of a singleton method of x
23 def x.show
24 puts self # prints the receiver
25 end
26
27 x.show
28 EXAMPLE 3 In the following program, the singleton method a of the class X is defined by a singleton
29 method definition.
30 class X
31 # The definition of a singleton method of the class X
32 def X.a
33 puts "The method a is invoked."
34 end
35 end
36 X.a
37 NOTE Singleton methods of a class is similar to so-called class methods in other object-oriendted
38 languages because they can be invoked on that class.
声明方式。
由于我无法发布答案,我将在此处添加答案:
看起来我的问题是针对ruby spec(或http://www.ipa.go.jp/osc/english/ruby/中的此部分量身定制的,以防直接链接无效。)
简而言之,这些是在Ruby中定义单例方法的3种不同方法。和
类的Singleton方法类似于所谓的类方法 其他对象定义语言,因为它们可以在其上调用 类。
x64