ruby - 如何在 Ruby 中初始化模块的实例变量?

标签 ruby module instance-variables

我有一些模块,我想在其中使用实例变量。我目前正在像这样初始化它们:

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 中初始化模块的实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/698300/

相关文章:

html - 在 Nokogiri 中选择变体

ruby-on-rails - 无法识别正确的 CSS 选择器以使用 Mechanize 进行抓取

css - 标题中 drupal 模块的位置

c++ - 初始化 vector 类型的静态类成员

python - 调用另一个类中的实例变量

ruby - 用两个数组中的值替换字符串(在 Ruby 中)

module - usemin revved 文件名和 requirejs 依赖项

JavaScript ES6 模块 : Avoid Polluting Global Namespace

python - 带前导双下划线的实例/类属性的意义和使用(特殊行为)

ruby-on-rails - 在 Ruby on Rails 中上传文件