[英]what does “$&” mean in Ruby
I notice one line code in spree library: 我注意到spree库中的一行代码:
label_with_first_letters_capitalized = t(options[:label]).gsub(/\b\w/)#{$&.upcase}
could someone tell me what does "$&" mean ? 有人能告诉我“$&”是什么意思吗? thanks!
谢谢!
Here is a reference to some of those special variables allowed in ruby . 这是对ruby中允许的一些特殊变量的引用 。 Basically, this one returns whatever the last pattern match was.
基本上,这个返回最后一次模式匹配。
From linked page: 来自链接页面:
$&
contains the matched string from the previous successful pattern match.$&
包含上一次成功模式匹配的匹配字符串。>> "the quick brown fox".match(/quick.*fox/) => #<MatchData:0x129cc40> >> $& => "quick brown fox"
In my testing, it appears to be the last match that gsub
got. 在我的测试中,它似乎是
gsub
得到的最后一场比赛。 So for instance, if I have this: 所以,例如,如果我有这个:
"Hello, world!".gsub(/o./, "a")
$&
would be set to or
, because that is the last match that gsub
encountered. $&
将被设置为or
,因为这是gsub
遇到的最后一个匹配。
$&
is the string that was matched by the last successful regex. $&
是最后一个成功的正则表达式匹配的字符串。 For example: 例如:
foobar = "foobar"
regex = /b.{2}/
if regex.match(foobar) then
puts $& # -> bar
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.