简体   繁体   English

如何将模块级函数导入Ruby中的类实例?

[英]How to import module level functions into class instance in Ruby?

module AA
  def func1()
  end

  class BB
    def method2()
      func1()
    end
  end

end

Currently method2 cannot find func1 and raises an exception. 当前method2找不到func1并引发异常。

Why does this happen and what is the right way to do this? 为什么会发生这种情况?正确的方法是什么?

This happens for a couple of reasons. 发生这种情况有两个原因。

Firstly, because things that belong to the AA module don't belong to the BB class. 首先,因为属于AA模块的东西不属于BB类。

Secondly, your syntax to define func1 isn't quite correct. 其次,您定义func1的语法不太正确。

See this example below of both defining the function (2 different ways) and calling it. 请参见下面的示例,同时定义函数(两种不同方式)并调用它。

module AA
  def self.func1
  end

  def AA.func2
  end

  class BB
    def method2()
      AA::func1()
    end
  end
end

The way that i follow is to include the module in your class definition 我遵循的方式是将模块包含在类定义中

 module AA
   def func1
     puts "func1"
     end
   class BB
    include AA
     def method2
      func1()
       end
     end
   end

This is a Module Mixin strategy, works for any class outside or inside a module. 这是一个模块混合策略,适用于模块外部或内部的任何类。 Please read the Mixin section at: http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html 请在以下网址阅读“混合”部分: http ://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html

Alternatively you could use the extend : 或者,您可以使用extend

module AA
  def func1()
  end

  class BB
    extend AA
    def method2()
      func1()
    end

  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM