开发者

what does "$&" mean in Ruby

开发者 https://www.devze.com 2023-03-15 00:35 出处:网络
I notice one line code in spree library: label_with_first_letters_capitalized = t(options[:label]).gsub(开发者_如何学C/\\b\\w/)#{$&.upcase}

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

精彩评论

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

关注公众号