require
searches for the file to load in the $LOAD_PATH
. require_relative
searches for the file relative to the directory where the file resides that the call to require_relative
is in. The two are completely different.
require './stacklike'
will look for the file in the current working directory. This is a really bad idea: if your script is in /home/ordek/myproject/bin/myscript.rb
and you are in /home/ordek/myproject
and call it like ruby bin/myscript.rb
, then the current working directory is /home/ordek/myproject
and require './stacklike'
will look for a file /home/ordek/myproject/stacklike.rb
. If you are in /home/ordek/myproject/bin
and call it like ./myscript.rb
, then your current working directory is /home/ordek/myproject/bin
and require './stacklike'
will look for a file /home/ordek/myproject/bin/stacklike.rb
.
In other words: which file gets loaded depends on circumstances outside the control of your script (after all, your script cannot influence from where it is called), which is not good (to say the least). In fact, it can allow an attacker to inject own code into your script, which can be disastrous.
For that reason, you should never rely on the current working directory when loading files.
For your situation, require_relative
is the only correct choice.