What is the difference between
require 'blahblahlblah.rb'
vs
require './blahblah.rb'
vs
require File.expand_path('../blahblah', __FILE__)
I see both of them being used. Wondering what's better, and under what circumstance is one better than the other.
Thanks!
require blaba.rb
is searching to your default gem path to load the file, which depends on the ruby version you are using. For example RVM will search in $HOME/.rvm/rubies/...
while a system wide ruby will search in the distribution's default path. Note that this is where gems are located, but you could manually add a library say mylibrary.rb
in the same path and use it in any of your programs. However, that's an awful thing to do, it's a much cleaner procedure to create gems and install them in your system.
require ./blabla.rb
loads a file that is sitting in your working directory. You could add the full path like require /home/username/library/myproject/models/sample.rb
. It will work just about the same. In the UNIX-like world the ./
sign means current directory. This solution is often used in irb
to load say a rails Model i.e. users.rb
into irb
or pry
and work with it. To give you an example in a shell environment (if you are familiar with UNIX shells, you'll figure it out):
GreyJewel ~ » ls myports.txt
myports.txt
GreyJewel ~ » ls ./myports.txt
./myports.txt
The third solution require File.expand_path('../sample.rb', __FILE__)
is used in programs, because it explicitly creates a full path using as an anchor the directory which the file holding the line sits, which is a much more secure approach compared to require ./sample.rb
. Note that when you load a ruby file, you can omit the file extension .rb
.
Hope this clarifies a bit the situation.
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