根据我所知道的,是的,但我对红宝石不熟悉,想确定一下。他们的工作有区别吗?有理由使用一种语法而不是另一种吗?
如果在类/模块的上下文之外使用,我确实知道class << self
并且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]
我见过Ruby 的 class << self vs self.method:什么更好?它没有谈论Foo.method
声明的方式。
由于我无法发布答案,因此我将在此处添加答案:
看起来我的问题是为ruby 规范中的本节量身定制的(或http://www.ipa.go.jp/osc/english/ruby/以防直接链接不起作用)。
简而言之,这是在 Ruby 中定义单例方法的 3 种不同方式。和:
类的单例方法类似于其他面向对象语言中所谓的类方法,因为它们可以在该类上调用。
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.