Ruby:是否可以在模块中定义类方法?
问题描述:
假设有三个类:A
、B
&C
.我希望每个类都有一个类方法,比如 self.foo
,它对 A
、B
和 B
具有完全相同的代码.C
.
Say there are three classes: A
, B
& C
. I want each class to have a class method, say self.foo
, that has exactly the same code for A
, B
& C
.
是否可以在模块中定义 self.foo
并将该模块包含在 A
、B
&C
?我尝试这样做,但收到一条错误消息,指出无法识别 foo
.
Is it possible to define self.foo
in a module and include this module in A
, B
& C
? I tried to do so and got an error message saying that foo
is not recognized.
答
module Common
def foo
puts 'foo'
end
end
class A
extend Common
end
class B
extend Common
end
class C
extend Common
end
A.foo
或者,您可以在之后扩展类:
Or, you can extend the classes afterwards:
class A
end
class B
end
class C
end
[A, B, C].each do |klass|
klass.extend Common
end