简体   繁体   中英

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? Do you ever need to require the module? When, and why?

You never require modules, you require files.

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

require "my_first_module"

before you could reference 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 .)

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. 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 ).

In the above example, before you can use MyFirstModule , you'll have to require the file that defines it.

Be aware that there is an auto loading mechanism which can require files automatically for you. Also, Rails does require most classes automatically. So don't be confused that in some cases a require statement does not seem to be necessary.

You do not need to require. 'Include' will expose the method say_hello to your class as you desire. 'Require' is used to pull in all the code from another file. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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