user2555452
user2555452

Reputation: 113

Require not able to find ruby file

I am an absolute beginner in Ruby. I created a small ruby file, and it runs well when I run the command ruby "methods.rb". That means I am in the correct directory.

But when I launch irb and run the command require "methods.rb", I get the following response:

LoadError: cannot load such file -- methods.rb
    from /usr/local/rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:53:in `require'
    from /usr/local/rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:53:in `require'
    from (irb):1
    from /usr/local/rvm/rubies/ruby-1.9.3-p392/bin/irb:16:in `<main>'

Upvotes: 7

Views: 2923

Answers (4)

vgoff
vgoff

Reputation: 11343

If you are going to load things in IRB that are in your current directory, you can do:

irb -I.

Note the 'dot' there, indicating current directory.

If you are exploring and making changes in that file, while you are in IRB, use load rather than `require as load lets you load your changes, and require will only allow the file to be required once. This means you will not need to exit IRB to see how your changes are being affected.

To find out what options you have for IRB, you can do irb --help which is good to do if you are learning the tool.

Upvotes: 1

Ruud Op Den Kelder
Ruud Op Den Kelder

Reputation: 31

To add the directory you are executing the ruby script from to the load path use:

$LOAD_PATH.unshift( File.join( File.dirname(__FILE__), '' ) ) 

or if you have put your dependencies in 'subdir' of the current directory:

$LOAD_PATH.unshift( File.join( File.dirname(__FILE__), 'subdir' ) ) 

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118299

I do have a ruby file called so.rb in the directory /home/kirti/Ruby. So first from IRB I would change my current working directory using Dir#chdir method. Then I would call #load or #require method. My so.rb file contains only p hello line.

I would go this way :

>> Dir.pwd
=> "/home/kirti"
>> Dir.chdir("/home/kirti/Ruby")
=> 0
>> Dir.pwd
=> "/home/kirti/Ruby"
>> load 'so.rb'
"hello"
=> true
>> require './so.rb'
"hello"
=> true

Upvotes: 1

Dylan Markow
Dylan Markow

Reputation: 124479

Ruby doesn't add the current path to the load path by default.

From irb, you can try require "./methods.rb" instead.

Upvotes: 10

Related Questions