Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, including module in current directory

Tags:

ruby

I am currently working through the Well Grounded Rubyist. Great book so far. I am stuck on something I don't quite get 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 have found online, the current directory isn't in the the namespace, so it can't see the file. But, the include statement doesn't take a string to let me give the path. Since the include statement and require statements do different things, I am absolutely lost as to how to get the include statement to recognize the module. I looked through other questions, but they all seem to be using the require statement. Any hints are greatly appreciated.

like image 469
Mark Freeman Avatar asked Feb 02 '23 16:02

Mark Freeman


1 Answers

You use require to load a file, not include. :-)

First, you have to require the file containing the module you want to include. Then you can include the module.

If you're using Rails, it has some magic to automagically require the right file first. But otherwise, you have to do it yourself.

like image 82
Chris Jester-Young Avatar answered Feb 05 '23 18:02

Chris Jester-Young