Ruby, including the module in the current directory

I am currently working on Well Grounded Rubyist. Great book. I'm stuck on something that I don't quite understand with ruby. I have two files

In ModuleTester.rb

class ModuleTester include MyFirstModule end mt = ModuleTester.new mt.say_hello 

In MyFirstModule.rb

 module MyFirstModule def say_hello puts "hello" end end 

When I run ruby ​​ModuleTester.rb, I get the following message:

ModuleTester.rb: 2: in <class:ModuleTester>': uninitialized constant ModuleTester::MyFirstModule (NameError) from ModuleTester.rb:1:in '

From what I found on the Internet, the current directory is not in the namespace, so it cannot see the file. But the include statement does not accept a string allowing me to specify a path. Since the include expression and require statements to do different things, I completely lost how to get the include statement to recognize the module. I looked at other questions, but they all seem to use the require statement. Any advice is appreciated.

+7
source share
2 answers

You use require to download the file, not include . include

First you need a require file containing the module you want to include . Then you can include module.

If you use Rails, it has some magic to automatically require correct file. But otherwise, you must do it yourself.

+8
source

You need a require file before you can use the types defined in it. *

 # my_first_module.rb module MyFirstModule def say_hello puts 'hello' end end 

Pay attention to require at the beginning of the following:

 # module_tester.rb require 'my_first_module' class ModuleTester include MyFirstModule end mt = ModuleTester.new mt.say_hello 

The require method actually loads and executes the specified script using the Ruby VM boot path ( $: or $LOAD_PATH ) to find it when the argument is not an absolute path.

The include method, on the other hand, actually mixes the current class in the Module methods. It is closely related to extend . The Well Grounded Rubyist does a great job of all this, so I urge you to continue to connect to it.

See # require , # include, and # expand docs for more information.


* When using Rubygems and / or the Bundler , but getting into these details is likely to confuse you more than it costs at this point.

+1
source

All Articles