Require that ruby ​​file cannot be found

I am completely new to Ruby. I created a small ruby ​​file and it works well when I run the ruby "methods.rb" command ruby "methods.rb" . This means that I am in the correct directory.

But when I run irb and run the require "methods.rb" command, 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>' 
+6
source share
4 answers

Ruby does not add the current path to the default boot path.

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

+10
source

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

I would go as follows:

 >> 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 
+1
source

To add the directory in which you are executing the ruby ​​script, use the boot path:

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

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

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

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

 irb -I. 

Pay attention to the "dot" indicating the current directory.

If you study and make changes to this file while you are in IRB, use load rather than `require , since load allows you to load your changes, and require only allows the file to be required once. This means that you will not need to exit the IRB to see how your changes are affected.

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

+1
source

Source: https://habr.com/ru/post/955118/


All Articles