What does the $ symbol mean in Ruby?

I played with Ruby on Rails for a while and decided to take a look at the actual source. Grabbed a repo from GitHub and started looking around. Found some code that I'm not sure what it is doing or what it is referencing.

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 refers to $: (aka "bling")?

+50
ruby ruby-on-rails
Dec 13 '09 at 15:53
source share
5 answers

$: global variable used to search for external files.

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

$: load the path for scripts and binary modules by loading or by request.

+31
Dec 13 '09 at 15:59
source share

$ identifies a global variable, not a local variable, an @instance variable, or a class variable @@.

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

+54
Dec 13 '09 at 16:31
source share

To quote the Ruby Forum:

ruby comes with a set of predefined variables

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

if I understood correctly (not 100% sure), this adds the lib path to this array of search paths by navigating the current file. which is not exactly the best way, I would just start with RAILS_ROOT (at least for rails the project)

+4
Dec 13 '09 at 16:00
source share
 $:.unshift 

coincides with

 $LOAD_PATH.unshift 

. You can also say:

 $: << $LOAD_PATH << 

They are pretty common Ruby idioms to set the download path.

+2
Dec 13 '09 at 16:08
source share

I want to point out something strange in Ruby!

$ really means the download path. A ; means "end of line". But!

$; means field separator. Try running $;.to_s in your REPL and you will see that it returns "," . That is not all! $ with other suffixes can mean many other things .

Why? Well, Perl, of course!

0
Nov 01. '17 at 2:06 on
source share



All Articles