ruby:使用模块包含类的实例方法

gou*_*ham 2 ruby module

看看下面的代码

initshared.rb
module InitShared
  def init_shared
    @shared_obj = "foobar"
  end
end
Run Code Online (Sandbox Code Playgroud)

myclass.rb

class MyClass
  def initialize()
  end
  def init
    file_name = Dir.pwd+"/initshared.rb"
    if File.file?(file_name)
      require file_name
      include InitShared
      if self.respond_to?'init_shared'
        init_shared
        puts @shared_obj
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

包含InitShared,因为它在方法内部不起作用.

我想检查文件,然后包含模块,然后访问该模块中的变量.

Kor*_*tor 9

而不是使用Samnang的

singleton_class.send(:include, InitShared)
Run Code Online (Sandbox Code Playgroud)

你也可以用

extend InitShared
Run Code Online (Sandbox Code Playgroud)

它也是如此,但与版本无关.它将模块仅包含在对象自己的单例类中.