Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "$," mean in ruby?

Tags:

ruby

I stumbled upon this piece of code in the rails source:

# File actionpack/lib/action_view/helpers/output_safety_helper.rb, line 30
def safe_join(array, sep=$,)
  sep ||= "".html_safe
  sep = ERB::Util.html_escape(sep)

  array.map { |i| ERB::Util.html_escape(i) }.join(sep).html_safe
end

What does $, do? I read the Regexp-documentation but I couldn't find anything about it.

like image 967
fabi Avatar asked May 29 '13 15:05

fabi


2 Answers

I finally found the answer myself here:

The output field separator for the print. Also, it is the default separator for Array#join. (Mnemonic: what is printed when there is a , in your print statement.)

The following code snippet shows the effect:

a = [1,2,3]

puts a.join # => 123

$, = ','
puts a.join # => 1,2,3
like image 54
fabi Avatar answered Oct 08 '22 13:10

fabi


The official documentation for the system variables is in:

http://www.ruby-doc.org/stdlib-2.0/libdoc/English/rdoc/English.html

A lot of Ruby's special variables are accessible via methods in various modules and classes, which hides the fact that the variable is what contains the value. For instance, lineno, available in IO and inherited by File, is the line number of the last line read by an IO stream. It's relying on $/ and $.

The "English" module provides long versions of the cryptic variables, making it more readable. Use of the cryptic variables isn't as idiomatic in Ruby as they are in Perl, which is why they're more curious when you run into them.

They come from a variety of sources: most, if not all, are immediately from Perl, but Perl inherited them from sed, awk, and the rest of its kitchen-sink collection of code. (It's a great language, really.)

There are other variables set by classes like Regexp, which defines variables for pre and post match, plus captures. This is from the documentation:

$~ is equivalent to ::last_match;
$& contains the complete matched text;
$` contains string before match;
$' contains string after match;
$1, $2 and so on contain text matching first, second, etc capture group;
$+ contains last capture group.

Though Ruby defines the short, cryptic, versions of the variables, it's recommended that we use require "English" to provide the long names. It's a readability thing, which translates to a long-term ease-of-maintenance thing.

like image 25
the Tin Man Avatar answered Oct 08 '22 11:10

the Tin Man