Ruby:是否可以在模块中定义类方法? [英] Ruby: Is it possible to define a class method in a module?

查看:39
本文介绍了Ruby:是否可以在模块中定义类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有三个类:AB &C.我希望每个类都有一个类方法,比如 self.foo,它对 ABB 具有完全相同的代码.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 并将该模块包含在 AB &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

这篇关于Ruby:是否可以在模块中定义类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆