When changing $ LOAD_PATH, why are you using unshift instead of push?

I believe the ruby ​​boot 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 the Ruby path array so we can request or load.

So, I hope to find out why we are not using push to add a file to the end of the array?

+4
source share
2 answers

Suppose you have a date.rb file (why not) and you want to download this file, not the standard library date.

If you use append, your file will never be loaded when you call require 'date', because it is at the end of the array, and the standard date will be found earlier.

, ,

+8

, concat - . unshift . , , , . <<(), , :

["a", "b"].concat(["c", "d"]) #=>  ["a", "b", "c", "d"]
["a", "b"].unshift("c").unshift("d") #=> ["d", "c", "a", "b"]
["a", "b"] << "c" << "d" #=>  ["a", "b", "c", "d"]

lib:

File.expand_path("../../lib", __FILE__)
#=> "/home/foo/lib/" #Note this is a string!

$:., . :

 $:.
 #=> ["/usr/local/lib/site_ruby/1.9.1", "/usr/lib/ruby/1.9.1/i686-linux"]

, :

 $:.unshift(File.expand_path("../../lib", __FILE__))
 #=> ["/home/foo/lib", "/usr/local/lib/site_ruby/1.9.1", "/usr/lib/ruby/1.9.1/i686-linux"]

concat , [] , :

  $:.concat([File.expand_path("../../lib", __FILE__)])
  #=> ["/usr/local/lib/site_ruby/1.9.1", "/usr/lib/ruby/1.9.1/i686-linux", "/home/lib"]
+2

All Articles