Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require not able to find ruby file

Tags:

ruby

irb

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>'
like image 297
user2555452 Avatar asked Oct 02 '13 16:10

user2555452


4 Answers

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

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

like image 114
Dylan Markow Avatar answered Sep 18 '22 18:09

Dylan Markow


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
like image 25
Arup Rakshit Avatar answered Sep 20 '22 18:09

Arup Rakshit


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' ) ) 
like image 29
Ruud Op Den Kelder Avatar answered Sep 19 '22 18:09

Ruud Op Den Kelder


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.

like image 34
vgoff Avatar answered Sep 21 '22 18:09

vgoff