Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require can't find an .rb file that's the same directory

Tags:

ruby

How exactly does the require command in Ruby work? I tested it with the following two files that are in the same directory.

test.rb

require 'requirements'
square(2)

requirements.rb

def square(x)
    x*x
end

But when I run ruby test.rb while I'm in the same directory as the files "test.rb" and "requirements.rb", I get the error:

/usr/local/rvm/rubies/ruby-1.9.3-p286/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- requirements (LoadError)
from /usr/local/rvm/rubies/ruby-1.9.3-p286/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from test.rb:1:in `<main>'

which I think means it can't find the requirements.rb file. But it's in the same directory as test.rb! How does one fix this?

Much thanks in advance. I apologize for such noob questions.

like image 528
User314159 Avatar asked Jan 10 '13 09:01

User314159


2 Answers

IIRC, ruby 1.9 doesn't include current dir ('.') to LOAD_PATH. You can do one of these:

# specify relative path
require './test1'

# use relative method
require_relative 'test1'

# add current dir to LOAD_PATH 
$LOAD_PATH.unshift '.'
require 'test1'
like image 173
Sergio Tulentsev Avatar answered Nov 02 '22 03:11

Sergio Tulentsev


I too just started to learn how ruby works, so I'm not perfectly sure if this helps. But try require_relative instead of require and I think it will work.
Afaik require searches in the ruby libary.

like image 40
Shimu Avatar answered Nov 02 '22 03:11

Shimu