Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does "$&" mean in Ruby

I notice one line code in spree library:

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

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

like image 499
why Avatar asked Jun 22 '11 03:06

why


People also ask

What the Fox say Meaning?

Speaking of the meaning of the song, Vegard characterizes it as coming from "a genuine wonder of what the fox says, because we didn't know". Although interpreted by some commentators as a reference to the furry fandom, the brothers have stated they did not know about its existence when producing "The Fox".

What does the fox say for real?

One of the most common fox vocalizations is a raspy bark. Scientists believe foxes use this barking sound to identify themselves and communicate with other foxes. Another eerie fox vocalization is a type of high-pitched howl that's almost like a scream.

What is this song Google?

Ask Google Assistant to name a song On your phone, touch and hold the Home button or say "Hey Google." Ask "What's this song?" Play a song or hum, whistle, or sing the melody of a song. Hum, whistle, or sing: Google Assistant will identify potential matches for the song.


2 Answers

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"
like image 199
drharris Avatar answered Sep 29 '22 11:09

drharris


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.

like image 39
Mark Szymanski Avatar answered Sep 29 '22 10:09

Mark Szymanski