假设有三个班:AB和;C.我希望每个类都有一个类方法,比如self.foo,对于AB和;C

是否可以在一个模块中定义self.foo,并在AB和amp;C? 我试图这么做,但收到一条错误消息,说foo无法识别.

推荐答案

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

或者,您可以在之后扩展这些类:

class A
end

class B
end

class C
end

[A, B, C].each do |klass|
  klass.extend Common
end

Ruby相关问答推荐

Ruby中链表大小调用的时间复杂度

Ruby反斜杠在新行上继续字符串?

如何在 Sinatra 中解析 JSON 请求正文一次并将其公开给所有路由?

使用 Homebrew 安装 Ruby

如何在不按 Enter 的情况下获取单个字符?

Ruby数组each_slice_with_index?

将haml标签放入link_to helper

在 Selenium WebDriver 中按 Ctrl + A

如何在 RSpec 2 中自动加载 spec_helper.rb

Ruby 数组中的奇数(或偶数)条目

为什么显式返回会对 Proc 产生影响?

如何理解 strptime 与 strftime

如何传递函数而不是块

如何在 Ruby 中使用全局变量或常量值?

检索/列出 Redis 数据库中的所有键/值对

Ruby中的字符串和符号有什么区别?

Eclipse 的首选 Ruby 插件?

在 Ruby 中创建二维数组和访问子数组

Ruby:如何将数组数组连接成一个

Rubocop 25 线块大小和 RSpec 测试