Hi; I’m a comp sci undergrad, with decent (maybe 6 months off and on)
Ruby/Rails experience. I’m competent with the syntax and have written a
number of Ruby scripts for various things.
Requiring local files always drove me nuts, due to the need to
explicitly declare the directory in the require statement with require
File.dirname(FILE) + ‘\somefile.rb’, which was rather bulky and
inelegant.
I stumbled onto a solution while reading about the array $:. I’ve hunted
for a solution like this many times, but never found it on Google
anywhere. The solution is this line, affixed to the top of the main
script file:
With this, a “require ‘somefile.rb’” statement for local files will work
for ANY file linked through all the scripts in the application. My
question is this: why do I not find this method used anywhere? Is there
some staggering disadvantage to doing this that did not occur to me?
I don’t understand this; if somefile.rb is in the same directory as
the file that’s requiring it, then why do you need the full path? Why
doesn’t
Sorry; I forgot to specify that the context I’m discussing is irb. For
hacking at scripts or examples, a lot of times I’ll make some variables
global and load the file into irb, then mess with the globals to figure
out how to do whatever I want.
Let’s say you have somefile.rb, which can contain anything. Then you
have the file someprog.rb, which contains:
require ‘somefile.rb’
In irb, if you type:
irb(main):001:0> load ‘c:/whatever/someprog.rb’
The prompt will blow up with a “no such file to load” error.
Requiring local files always drove me nuts, due to the need to
explicitly declare the directory in the require statement with require
File.dirname(FILE) + ‘\somefile.rb’, which was rather bulky and
inelegant.
I don’t understand this; if somefile.rb is in the same directory as
the file that’s requiring it, then why do you need the full path? Why
doesn’t
require ‘somefile.rb’
work by itself?
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.