What does the "$" character mean in Ruby?
Asked Answered
S

5

65

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?

Syncretism answered 13/12, 2009 at 15:53 Comment(0)
G
40

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

From https://docs.ruby-lang.org/en/3.2/globals_rdoc.html

$LOAD_PATH - Load path for searching Ruby scripts and extension libraries used by Kernel#load and Kernel#require. Aliased to $: and $-I

Gerardgerardo answered 13/12, 2009 at 15:59 Comment(0)
S
76

$ 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

Shakira answered 13/12, 2009 at 16:31 Comment(0)
G
40

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

From https://docs.ruby-lang.org/en/3.2/globals_rdoc.html

$LOAD_PATH - Load path for searching Ruby scripts and extension libraries used by Kernel#load and Kernel#require. Aliased to $: and $-I

Gerardgerardo answered 13/12, 2009 at 15:59 Comment(0)
C
9

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!

Contrary answered 1/11, 2017 at 2:6 Comment(1)
Thanks, this was what I was looking for i.e. the use of $ in defining field separators among many other things.Befuddle
F
4

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)

Faucher answered 13/12, 2009 at 16:0 Comment(0)
B
3
$:.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.

Bridgetbridgetown answered 13/12, 2009 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.