I don't understand the meaning of $:<< "."
in Ruby.
I upgraded Ruby to 1.9.1, but a program was not working. My classmate told me that I am supposed to add $:<< "."
What does $:<< "."
do?
I don't understand the meaning of $:<< "."
in Ruby.
I upgraded Ruby to 1.9.1, but a program was not working. My classmate told me that I am supposed to add $:<< "."
What does $:<< "."
do?
$:
is the variable that holds an array of paths that make up your Ruby's load path<<
appends an item to the end of the array.
refers to the current directorySo you are adding the current directory to Ruby's load path
References:
Can be found in the
Execution Environment Variables
section of of this page from The Pragmatic Programmers GuideCan be found in the docs for array at ruby-doc.org.
Since version 1.9, Ruby doesn't look for required files in the current working directory AKA
.
. The$LOAD_PATH
or$:
global variable is an array of paths where Ruby looks for files yourequire
.By adding
$:<< "."
to your files, you are actually telling Ruby to include your current directory in the search paths. That overrides new Ruby behavior.In your example you add working directory (
"."
) to ruby load path ($:
).Working directory (
"."
) was removed from load path (global variable$:
or$-I
or$LOAD_PATH
) in Ruby 1.9 because it was considered a security risk:And you have alike project:
If you run Project1 from Project2 folder, then main1.rb will require Project2/init.rb, not Project1/init.rb:
You can change your working directory in your code, e.g. using
Dir.chdir
:I recommend you to use the following techniques instead of
$: << '.'
:require_relative (Ruby 1.9 only)
Add folder of the file to the working directory (common approach because it is compatible with Ruby 1.8):
$: << File.expand_path('..', __FILE__) etc.
.__FILE__
is a reference to the current file name. File.expand_path converts a pathname to an absolute pathname.