示例 1:
class Dog
def self.class_method
:another_way_to_write_class_methods
end
end
def test_you_can_use_self_instead_of_an_explicit_reference_to_dog
assert_equal :another_way_to_write_class_methods, Dog.class_method
end
示例 2:
class Dog
class << self
def another_class_method
:still_another_way
end
end
end
def test_heres_still_another_way_to_write_class_methods
assert_equal :still_another_way, Dog.another_class_method
end
我可以知道在 Ruby 中首选哪种编写类方法的方式吗?为什么?是否存在优先于另一个的情况?
最佳答案
您要求使用不同的方法来创建类方法。这里有一些。
class A
def self.a
"A"
end
end
A.a #=> "A"
class B
class << self
def b
"B"
end
end
end
B.b #=> "B"
class C
singleton_class.class_eval do
def c
"C"
end
end
end
C.c #=> "C"
module M
def m
"M"
end
end
class D
extend M
end
D.m #=> "M"
class E
class << self
include M
end
end
E.m #=> "M"
class F
singleton_class.instance_eval do
define_method(:f) do
"F"
end
end
end
F.f #=> "F"
如果:f
是动态创建的,
class F
end
F.singleton_class.instance_eval do
define_method(:f) do
"F"
end
end
或变体:
F.singleton_class.instance_eval "define_method(:f) { 'F' }"
F.f #=> "F"
class Class
def k
"K"
end
end
class G
end
G.k #=> "K"
这里的问题是 Class
的所有实例方法(包括 :k
)都可供所有类用作(类)方法,因为类是类
(H.class#=>类
)。
class Object
def o
"O"
end
end
class H
end
H.o #=> "O"
H.new.o #=> "O"
这个很有趣。 Object
是 Class
的祖先(Class.ancestors #=> [Class, Module, Object, Kernel, BasicObject]
),所以 Class
从Object
继承实例方法:o
。因此(从前面的例子来看),:o
是 H
的一个类方法。但是,H
也是Object
的子类(H.superclass #=> Object
),所以H
继承实例方法Object#:o
。
至于哪个是“最好的”,这取决于。如果只创建几个类方法,大多数将使用 A
。如果需要大量数据,我会使用 D
或 B
。如果要动态创建类方法,F
或一些变体。但是,我无法想象我会使用 G
或 H
的情况。
关于ruby - 在 Ruby 中创建类方法的不同方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39936920/