Require not able to find ruby file

假装没事ソ 提交于 2019-12-01 17:36:17

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!