What does the "$" character mean in Ruby?

Ruby on-RailsRubyGlobal VariablesDollar SignLoad Path

Ruby on-Rails Problem Overview


Been playing with Ruby on Rails for awhile and decided to take a look through the actual source. Grabbed the repo from GitHub and started looking around. Came across some code that I am not sure what it does or what it references.

I saw this code in actionmailer/test/abstract_unit.rb

root = File.expand_path('../../..', __FILE__)
 begin
 require "#{root}/vendor/gems/environment"
 rescue LoadError
 $:.unshift("#{root}/activesupport/lib")
 $:.unshift("#{root}/actionpack/lib")
end

lib = File.expand_path("#{File.dirname(__FILE__)}/../lib")
$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)

require 'rubygems'
require 'test/unit'

require 'action_mailer'
require 'action_mailer/test_case'

Can someone tell me what the $: (a.k.a. "the bling") is referencing?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

$ identifies a global variable, as opposed to a local variable, @instance variable, or @@class variable.

Among the language-supplied global variables are $:, which is also identified by $LOAD_PATH

Solution 2 - Ruby on-Rails

$: is the global variable used for looking up external files.

From http://www.zenspider.com/Languages/Ruby/QuickRef.html#18

> $: Load path for scripts and binary modules by load or require.

Solution 3 - Ruby on-Rails

I wanna note something weird about Ruby!

$ does indeed mean load path. And ; means "end line". But!

$; means field separator. Try running $;.to_s in your REPL and you'll see it return ",". That's not all! $ with other suffixes can mean many other things.

Why? Well, Perl of course!

Solution 4 - Ruby on-Rails

To quote the Ruby Forum:

ruby comes with a set of predefined variables

$: = default search path (array of paths)
__FILE__ = current sourcefile

if i get it right (not 100% sure) this adds the lib path to this array of search paths by going over the current file. which is not exactly the best way, i would simply start with RAILS_ROOT (at least for a rails project)

Solution 5 - Ruby on-Rails

$:.unshift

is the same as

$LOAD_PATH.unshift

. You can also say:

$: <<
$LOAD_PATH <<

They are pretty common Ruby idioms to set a load path.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionScott RadcliffView Question on Stackoverflow
Solution 1 - Ruby on-RailsJustin LoveView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMark ByersView Answer on Stackoverflow
Solution 3 - Ruby on-RailsAlex Moore-NiemiView Answer on Stackoverflow
Solution 4 - Ruby on-RailsJustin EthierView Answer on Stackoverflow
Solution 5 - Ruby on-RailsTK.View Answer on Stackoverflow