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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With