Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $:<< "." do to Ruby's require path?

Tags:

ruby

require

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?

like image 690
user997948 Avatar asked Dec 26 '11 13:12

user997948


2 Answers

  1. $: is the variable that holds an array of paths that make up your Ruby's load path
  2. << appends an item to the end of the array
  3. . refers to the current directory

    1   2  3
    |   |  |
    V   V  V
    $: << "."
    

So you are adding the current directory to Ruby's load path

References:

  1. Can be found in the Execution Environment Variables section of of this page from The Pragmatic Programmers Guide

    An array of strings, where each string specifies a directory to be searched for Ruby scripts and binary extensions used by the load and require methods. The initial value is the value of the arguments passed via the -I command-line option, followed by an installation-defined standard library location, followed by the current directory (“.”)[Obviously this link is for an older version of Ruby as this is still in there]. This variable may be set from within a program to alter the default search path; typically, programs use $: << dir to append dir to the path.

  2. Can be found in the docs for array at ruby-doc.org.

    Append—Pushes the given object on to the end of this array. This expression returns the array itself, so several appends may be chained together.

like image 134
Paul.s Avatar answered Sep 29 '22 16:09

Paul.s


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 you require.

By adding $:<< "." to your files, you are actually telling Ruby to include your current directory in the search paths. That overrides new Ruby behavior.

like image 28
Yossi Avatar answered Sep 29 '22 15:09

Yossi