什么是 Ruby 编号的全局变量 [英] What are Ruby's numbered global variables

查看:41
本文介绍了什么是 Ruby 编号的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$1、$2、$'、$` 在 Ruby 中的含义是什么?

What do the values $1, $2, $', $` mean in Ruby?

推荐答案

它们是从最近的模式匹配中捕获的(就像在 Perl 中一样;Ruby 最初从 Perl 中提取了很多语法,尽管它在很大程度上被现在 :).$1$2 等引用正则表达式中括号内的捕获:给定 /a(.)b(.)c/, $1 将是 ab$2 之间的字符 b 和 <代码>c.$`$' 分别表示匹配整个正则表达式的字符串前后的字符串(它本身在 $& 中).

They're captures from the most recent pattern match (just as in Perl; Ruby initially lifted a lot of syntax from Perl, although it's largely gotten over it by now :). $1, $2, etc. refer to parenthesized captures within a regex: given /a(.)b(.)c/, $1 will be the character between a and b and $2 the character between b and c. $` and $' mean the strings before and after the string that matched the entire regex (which is itself in $&), respectively.

这些实际上是有一定意义的,如果只是在历史上的话;您可以在 perldoc perlvar 中找到它,它通常在记录 Perl 变量的预期助记符和历史记录方面做得很好,并且主要仍然适用于 Ruby 中的全局变量.编号捕获是捕获反向引用正则表达式语法(\1\2 等)的替代;Perl 在 3.x 版本的某个地方从前者切换到后者,因为在正则表达式之外使用反向引用语法使解析过于复杂.(到 Perl 5 推出时,解析器已经被充分重写,语法再次可用,并迅速重新用于引用/指针".Ruby 选择使用名称引用 : 代替,这更接近于 Lisp 和 Smalltalk 风格;因为 Ruby 一开始是类似 Perl 的 Smalltalk 风格 OO,这在语言上更有意义.)同样适用于 $&,在历史上正则表达式语法只是 & (但你不能在替换的替换部分之外使用它,所以它变成了一个变量 $& ).$`$' 都是可爱的":匹配字符串中的反引号"和前引号".

There is actually some sense to these, if only historically; you can find it in perldoc perlvar, which generally does a good job of documenting the intended mnemonics and history of Perl variables, and mostly still applies to the globals in Ruby. The numbered captures are replacements for the capture backreference regex syntax (\1, \2, etc.); Perl switched from the former to the latter somewhere in the 3.x versions, because using the backreference syntax outside of the regex complicated parsing too much. (By the time Perl 5 rolled around, the parser had been sufficiently rewritten that the syntax was again available, and promptly reused for references/"pointers". Ruby opted for using a name-quote : instead, which is closer to the Lisp and Smalltalk style; since Ruby started out as a Perl-alike with Smalltalk-style OO, this made more sense linguistically.) The same applies to $&, which in historical regex syntax is simply & (but you can't use that outside the replacement part of a substitution, so it became a variable $& instead). $` and $' are both "cutesy": "back-quote" and "forward-quote" from the matched string.

这篇关于什么是 Ruby 编号的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆