Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When changing the $LOAD_PATH, why do you use unshift instead of push?

Tags:

ruby

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?

like image 275
wonderflow Avatar asked Jan 21 '14 09:01

wonderflow


People also ask

What is $Load_path?

$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.

What is ruby load path?

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'


1 Answers

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

like image 159
Intrepidd Avatar answered Sep 22 '22 18:09

Intrepidd