我想在一些模块中使用实例变量.我目前正在初始化它们,如下所示:

module MyModule
  def self.method_a(param)
    @var ||= 0
    # other logic goes here
  end
end

我还可以调用init方法来初始化它们:

def init
  @var = 0
end

但这意味着我必须记住要经常打电话给它.

有更好的方法吗?

推荐答案

在模块定义中初始化它们.

module MyModule
  # self here is MyModule
  @species = "frog"
  @color = "red polka-dotted"
  @log = []

  def self.log(msg)
    # self here is still MyModule, so the instance variables are still available
    @log << msg
  end
  def self.show_log
    puts @log.map { |m| "A #@color #@species says #{m.inspect}" }
  end
end

MyModule.log "I like cheese."
MyModule.log "There's no mop!"
MyModule.show_log #=> A red polka-dotted frog says "I like cheese."
                  #   A red polka-dotted frog says "There's no mop!"

这将在定义模块时设置实例变量.请记住,您可以稍后重新打开该模块以添加更多实例变量和方法定义,

# continued from above...
module MyModule
  @verb = "shouts"
  def self.show_log
    puts @log.map { |m| "A #@color #@species #@verb #{m.inspect}" }
  end
end
MyModule.log "What's going on?"
MyModule.show_log #=> A red polka-dotted frog shouts "I like cheese."
                  #   A red polka-dotted frog shouts "There's no mop!"
                  #   A red polka-dotted frog shouts "What's going on?"

Ruby相关问答推荐

数组上的Ruby#unionreact 非常奇怪

为什么 ruby​​ 获得证书信任链与 gnutls-cli 不同

配置 SubLime Linter 插件以使用 Ruby 1.9 语法

Jekyll 默认安装没有 _layouts 目录

Ruby vs Scala - 各自的优缺点

需要在Ruby中将数组拆分为指定大小的子数组

在 Ruby 中为类添加实例变量

检测 ruby​​ 是否在 Windows 上运行的正确方法是什么?

在 Go (golang) 中编写一个 Ruby 扩展

ruby:对两个或多个数组的对应成员求和

如何在 Ruby 中初始化 Hash 中的数组

将一个目录的内容复制到另一个目录

Rails 类 << self

无法在 OSX Lion 上使用 RVM 安装 Ruby 企业版

Ruby 中数组和哈希的性能

文字数字中的下划线是什么意思?

相当于 Ruby 中的通过

用 Ruby 解析 XML

使用 Liquid 标记在 Jekyll 中获取今天的日期

通过多个分隔符拆分字符串