简体   繁体   English

什么时候需要Ruby中的模块?

[英]When do you have to require a module in Ruby?

Say you have 说你有

module MyFirstModule
  def say_hello
    puts "Hello"
  end
end

and

class ModuleTester
  include MyFirstModule
end

Do you need a require MyFirstModule statement above the class definition? 在类定义之上是否需要一个require MyFirstModule语句? Do you ever need to require the module? 你有没有需要这个模块? When, and why? 什么时候,为什么?

You never require modules, you require files. 你永远require模块,你require文件。

In the above example, if the two fragments that you posted were in different files, eg my_first_module.rb and module_tester.rb , then you would have to do 在上面的示例中,如果您发布的两个片段位于不同的文件中,例如my_first_module.rbmodule_tester.rb ,那么您将不得不这样做

require "my_first_module"

before you could reference MyFirstModule . 在你可以引用MyFirstModule之前。

(Obviously, if they were in the same file, no require statement would be necessary, and would not make sense anyway, as there would be no file to require .) (显然,如果他们是在同一个文件,没有require声明将是必要的,而且是没有意义反正就没有文件require 。)

What require does is to look for the given Ruby file in the library path , and then load the Ruby file, just as if you had executed it. require做的是在库路径中查找给定的Ruby文件,然后加载Ruby文件,就像执行它一样。 The file will be loaded at most once during the runtime of your program (which is the difference to the load command, which is otherwise very similar to require ). 在程序运行期间,该文件最多将被加载一次(这与load命令的区别在于,这与require非常相似)。

In the above example, before you can use MyFirstModule , you'll have to require the file that defines it. 在上面的示例中,在使用MyFirstModule之前,您必须require定义它的文件。

Be aware that there is an auto loading mechanism which can require files automatically for you. 请注意,有一个自动加载机制,可以自动为您require文件。 Also, Rails does require most classes automatically. 此外,Rails确实require大多数类自动。 So don't be confused that in some cases a require statement does not seem to be necessary. 因此,不要混淆在某些情况下似乎没有必要使用require语句。

You do not need to require. 你不需要。 'Include' will expose the method say_hello to your class as you desire. 'Include'会根据您的需要将方法say_hello暴露给您的班级。 'Require' is used to pull in all the code from another file. 'Require'用于从另一个文件中提取所有代码。 So if you had defined MyFirstModule in another file, you would require that file so that you could then include the module in your class. 因此,如果您在另一个文件中定义了MyFirstModule,则需要该文件,以便您可以在该类中包含该模块。

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

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