Require not able to find ruby file
Asked Answered
L

4

7

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>'
Lani answered 2/10, 2013 at 16:36 Comment(0)
B
10

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

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

Burnight answered 2/10, 2013 at 16:40 Comment(0)
I
1

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
Isomer answered 2/10, 2013 at 16:47 Comment(0)
B
1

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' ) ) 
Bernete answered 2/10, 2013 at 17:42 Comment(0)
B
1

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.

Blas answered 2/10, 2013 at 18:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.