Hey everyone! I am having trouble with understanding modules -- I have two files, one named "modfile.rb" with the module, and one named "main.rb" that runs the code:
# modfile.rb
module Module1
def method1
puts "SUCCESS!"
end
end
# main.rb
require 'modfile'
Module1.method1
Unfortunately, instead of SUCCESS! appearing on my screen, I get this:
<internal:lib/rubygems/custom_require>:29:in 'require': no such file to load -- modfile (LoadError)
from <internal:lib/rubygems/custom_require>:29:in 'require'
from main.rb:1:in '<main>'
I think (though I may be wrong) that Ruby is looking to the lib/.... file inside the Ruby directory on my computer, while modfile.rb is saved in the same directory as main.rb. How do I fix this problem (other than by moving the module's file?)
PS. one guide suggested I add the line "require 'rubygems'" but I already did and got 开发者_Python百科the same error.
Check into the differences between require
and require_relative
in Ruby: require vs require_relative - best practice to workaround running in both Ruby <1.9.2 and >=1.9.2
In Ruby 1.9 the .
directory was removed from the search path. To fix the problem this generated they added require_relative
.
If modfile.rb and main.rb are in the same directory, make sure that you aare calling main.rb from the directory it's in, ie:
ruby main.rb
As I believe that is the directory that the Ruby interpreter will be looking in for any require files.
Edit: as @the-tin-man points out, the behaviour has changed for Ruby 1.9.
To be completely on the safe side, you can do:
require File.join(File.dirname(__FILE__), "modfile")
One other thing:
def method1
... should be:
def self.method1
... since you are calling the method as a class level method.
精彩评论