【问题标题】:can I call a function to define a variable in a module definition?我可以调用函数来定义模块定义中的变量吗?
【发布时间】:2020-05-13 20:59:33
【问题描述】:

我想在我的模块加载时定义变量@@importers。

module Importers
  @@importers_dir = File.dirname(__FILE__) + '/services/'
  @@importers = self.load_and_instantiate()
  def self.load_and_instantiate()
     #mycode here
  end
end

但它不起作用:

进口商的未定义方法'load_and_instantiate':模块 (NoMethodError)

我应该如何处理?

谢谢!

【问题讨论】:

  • 我没有看到在模块中定义的类变量(并且很少看到在任何地方定义的类变量,这是有充分理由的)。我假设您意识到如果 Importers 包含在一个类中,该类将获取那些具有计算值的类变量(例如,module M; @@v = 1; end; class C; include M; end; C.class_variable_get(:@@v) #=> 1)。如果创建Importers::load_and_instantiate 只是为了给@@importers 赋值,那么只需写@@importers = #mycode here。最后,不带参数调用方法时,通常不会显示空括号。

标签: ruby module


【解决方案1】:

在您调用load_and_instantiate 时,它确实没有定义,因为您稍后在代码中定义了它。

只要在定义方法后改变顺序并调用方法即可:

def self.load_and_instantiate
  # mycode here
end

@@importers = self.load_and_instantiate

请注意,在 Ruby 中使用类变量并不常见。

【讨论】:

  • @gordie 大多数时候是class instance variable
  • ...或@@importers = load_and_instantiate,作为load_and_instantiate的接收者,如果未指定,则等于self
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 2015-01-03
  • 1970-01-01
  • 1970-01-01
  • 2010-11-25
  • 2019-09-29
  • 1970-01-01
相关资源
最近更新 更多