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>'
Ruby doesn't add the current path to the load path by default.
From irb, you can try require "./methods.rb"
instead.
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
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' ) )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With