Reputation: 91
cat module1.rb =>
module Module1
def add(a,b)
return a+b
end
def subtract(a,b)
return a-b
end
end
cat call.rb =>
#!/home/user1/.rvm/rubies/ruby-1.9.2-p180/bin/ruby
include './Module1.rb
temp = add(5,2)
print temp
print "\n"
ruby call.rb =>
<internal:lib/rubygems/custom_require>:29:in `require': no such file to load -- Module1 (LoadError)
from <internal:lib/rubygems/custom_require>:29:in `require'
from call.rb:3:in `<main>'
Can anyone fix it ?
Upvotes: 1
Views: 6372
Reputation: 369624
require
loads a file from Ruby's $LOAD_PATH
. If you want to load a file relative to the current file, then you need to use require_relative
instead.
Upvotes: 2
Reputation: 7622
You should require the file before including.
require 'module1.rb'
include Module1
And make sure the two file are in same directory.
Upvotes: 0
Reputation: 88478
Place two files in the same directory. Call the first one module1.rb and make it look exactly like this:
module Module1
def add(a, b)
return a + b
end
def subtract(a, b)
return a - b
end
end
Call the second one call.rb and make it look exactly like this
require './module1.rb'
include Module1
temp = add(5,2)
print temp
print "\n"
At the commandline, run ruby call.rb
. You should see an output of 7
.
Upvotes: 4
Reputation: 39650
I assume you're using Ruby 1.9?
Then try
require_relative 'module1'
include Module1
temp = add(5,2)
puts temp
That should do it.
Upvotes: 2