9

I'm working with Ruby 1.8 and I have script that I want to call but it's in a parent folder. Below is the structure:

maindir/
neededscript.rb
  subdir/
    subdir2/
      myscript.rb

How can I require neededscript.rb from inside myscript.rb?

toro2k
  • 19,020
  • 7
  • 64
  • 71
zulqarnain
  • 1,695
  • 1
  • 16
  • 33

3 Answers3

7

In Ruby >=1.9 you can use the require_relative method

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.

require_relative '../../neededscript.rb'
fullybaked
  • 4,117
  • 1
  • 24
  • 37
  • Sorry for the late comment but as I mentioned am using ruby 1.8.*. – zulqarnain Jun 03 '13 at 11:37
  • Ah no worries. Just for context, I'll point out that the version wasn't in the question when I answered :) but was edited in after. For version ~ 1.8 either of the other 2 answers are good. – fullybaked Jun 03 '13 at 11:45
6

You can also add the path to the ruby libs path by adding these lines to myscript.rb before doing the require

binpath = File.dirname( __FILE__ )
$:.unshift File.expand_path( File.join( binpath, ".." ) )
sethi
  • 1,869
  • 2
  • 17
  • 27
5

This is what I've done instead:

File.expand_path("../../neededsript.rb",File.dirname(__FILE__))
zulqarnain
  • 1,695
  • 1
  • 16
  • 33