开发者

what does "$&" mean in Ruby

I notice one line code in spree library:

label_with_first_letters_capitalized = t(options[:label]).gsub(开发者_如何学C/\b\w/)#{$&.upcase}

could someone tell me what does "$&" mean ? thanks!


Here is a reference to some of those special variables allowed in 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. 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.


$& 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜