What does "$" mean in ruby?

I came across this piece of code in a 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 makes $, ,? I read the Regexp documentation , but I could not find anything.

+6
source share
2 answers

I finally found the answer here :

Separator of output fields for printing. Also, this is the default delimiter for the Array # connection. (Mnemonics: what is printed when there is, in your print application.)

The following code snippet shows the effect:

 a = [1,2,3] puts a.join # => 123 $, = ',' puts a.join # => 1,2,3 
+5
source

Official documentation for system variables:

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

Many special Ruby variables are accessible through methods in various modules and classes, which hides the fact that the variable is what contains the value. For example, lineno , available in IO and inherited by a file, is the line number of the last line read by the I / O stream. He relies on $/ and $.

The "English" module provides long versions of critical variables, which makes it more readable. Using critical variables is not as idiomatic in Ruby as it is in Perl, so they are more curious when you come across them.

They come from a variety of sources: most, if not all, are directly from Perl, but Perl inherited them from sed, awk, and the rest of the kitchen code collection. (This is actually a great language.)

There are other variables defined by classes such as Regexp , which defines variables for the pre and post match, as well as for 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. 

Although Ruby defines short, cryptic versions of variables, it is recommended that you use require "English" to provide long names. This is readability, which translates into long-term ease of maintenance.

+5
source

Source: https://habr.com/ru/post/946096/


All Articles