Jes Jes - 6 months ago 18
Ruby Question

Ruby - regular expressions, $1

I'm learning about regular expressions in Ruby and I'm stuck with one example - it's supposed to transform

snake_case
to
CamelCase
.

The way I understood
$1
variable was: it's the first matched (to a regexp) letter. So I would expect
gsub(/_(.)/)
is going to match
c
after
_
in string
camel_case
, so it will become capital letter.

But if so - why has
_
dissapeared? It works like it's substituting
_
with capital letter, but in this case,
_
would be a match -
$1
. Can someone please explain?

def zebulansNightmare(string)
string.gsub(/_(.)/){$1.upcase}
end

Answer

You are right that $1 is the captured value, however, the gsub matches the letter with _ before it, and the whole match gets replaced. You need to reinsert _ to the result:

"camel_case".gsub(/_(.)/){"_#{$1.upcase}"}

See the IDEONE demo

BTW, if you only plan to match _ followed with a letter (so as not to waste time and resources on trying to turn non-letters to upper case), you can use the following regex:

/_(\p{Ll})/

Where \p{Ll} is any lowercase Unicode letter.