我有一些模块,我想在其中使用实例变量.我目前正在初始化它们:
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?"
您可以使用:
def init(var=0) @var = var end
如果你没有传递任何东西,它将默认为0.
如果你不想每次都打电话,你可以使用这样的东西:
module AppConfiguration mattr_accessor :google_api_key self.google_api_key = "123456789" ... end