2011-06-22 50 views
8

我注意到大礼包库一行代码:

label_with_first_letters_capitalized = t(options[:label]).gsub(/\b\w/)#{$&.upcase} 

有人能告诉我什么是“$ &”是什么意思?谢谢!

回答

8

这是reference to some of those special variables allowed in ruby。基本上,这个返回最后的模式匹配。

从链接页面:

$&包含从以前成功的模式匹配匹配的字符串。

>> "the quick brown fox".match(/quick.*fox/) 
=> #<MatchData:0x129cc40> 
>> $& 
=> "quick brown fox" 
+0

此链接不好 – ebrohman

+0

@ebrohman谢谢,链接到wayback归档版本。 – drharris

+0

@drharris:也可以直接在答案中包含页面的相关部分? –

3

在我的测试,它似乎是最后一场比赛是gsub了。因此,举例来说,如果我有这样的:

"Hello, world!".gsub(/o./, "a") 

$&将被设置为or,因为这是gsub遇到的最后一场比赛。

1

$&是最后一次成功的正则表达式匹配的字符串。例如:

foobar = "foobar" 
regex = /b.{2}/ 

if regex.match(foobar) then 
    puts $& # -> bar 
end