I find ruby load path is an array, and many projects use it like this:
$:.unshift(File.expand_path("../../lib", __FILE__))
It can add local files to the front of ruby path array to enable us require or load.
So, I hope to know why don't we use push to add the file at the end of the array?
$LOAD_PATH is an array of absolute paths i.e it stores the exact location of all the dependencies in the project. The require keyword searches for the dependencies in the array $LOAD_PATH and tries to load it for the file that has a dependency on certain library.
Ruby by default has a list of directories it can look through when you ask it to load a specific file. This is stored in a variable: $: This is the load path. It initially includes the libdir, archdir, sitedir, vendordir and some others and is information Ruby holds about itself. If you type ruby -e 'puts $LOAD_PATH'
Let's assume you have a "date.rb" file (why not) and you want to load this file, and not the standard library date.
If you use append, your file will never be loaded when you call require 'date'
because it's located at the end of the array and the standard date will be found before.
Therefore, if you prepend your path to the load path, you don't risk priority lookup
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