Adding a directory to $LOAD_PATH (Ruby)

ghz 1years ago ⋅ 7798 views

Question

I have seen two commonly used techniques for adding the directory of the file currently being executed to the $LOAD_PATH (or $:). I see the advantages of doing this in case you're not working with a gem. One seems more verbose than the other, obviously, but is there a reason to go with one over the other?

The first, verbose method (could be overkill):

$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__))) unless $LOAD_PATH.include?(File.expand_path(File.dirname(__FILE__)))

and the more straightforward, quick-and-dirty:

$:.unshift File.dirname(__FILE__)

Any reason to go with one over the other?


Answer

I would say go with $:.unshift File.dirname(__FILE__) over the other one, simply because I've seen much more usage of it in code than the $LOAD_PATH one, and it's shorter too!