1

I have the following problem:

My ruby project structure : Ruby_Source\ file1.rb file2.rb file3.rb

In file1.rb, require 'file2' require 'file3'

now ,if I run the file1.rb from Ruby_Source, am not getting any error.

but , when I run the same from a different system location eg(c:)

error is Load error.

Can some one help me please?

vineel
  • 205
  • 2
  • 4
  • 9

2 Answers2

3

You might want to use require_relative:

require_relative complements the builtin method require by allowing you to load a file that is relative to the file containing the require_relative statement.

See further discussion:

What is the difference between require_relative and require in Ruby?

And if you run Ruby 1.8:

Ruby: require vs require_relative - best practice to workaround running in both Ruby <1.9.2 and >=1.9.2

Community
  • 1
  • 1
Casper
  • 33,403
  • 4
  • 84
  • 79
0

Try this:

require_relative 'file2'

in Ruby 1.9.x. It will search for file2 in the directory of file1.

In older versions you might try something like:

$: << File.dirname($0) 

which will add the current program's path to the require-search path.

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
  • Please don't do the latter. In older versions you might want to do something like `require File.expand_path('../file2', __FILE__)` no need to alter the $LOAD_PATH – Lee Jarvis Sep 04 '12 at 14:52
  • Modifying the LOAD_PATH is a potential security risk, and it's really NEVER necessary in library code, there's always better alternatives – Lee Jarvis Sep 04 '12 at 16:45
  • @injekt: Since `'.'` is already part of `$LOAD_PATH` (in Ruby 1.8.x), I cannot see an additional security risk by adding the directory of the program. And I was not aware we are talking about libraries. – undur_gongor Sep 05 '12 at 06:33
  • Exactly, it's path of the LOAD_PATH pre 1.9, the reason it was changed was due to security risk, why would we want to undo these changes? The OP hasn't given enough information to tell if we're talking about libraries or not, but it shouldn't matter. You never NEED to modify the LOAD_PATH, so I try to avoid newbies thinking it's okay and before you know it, there's ugly security risk requires all over mainstream code – Lee Jarvis Sep 05 '12 at 07:33