Jes Jes - 1 year ago 82
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


The way I understood
variable was: it's the first matched (to a regexp) letter. So I would expect
is going to match
in string
, 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 -
. Can someone please explain?

def zebulansNightmare(string)

Answer Source

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:


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:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download