sub
accepts an optional block instead of a replacement parameter. If given, it places the sub-matches into global variables, invokes the block, and returns the matched portion of the string with the block's return value.
The regular expression in question finds the first character at the beginning of a line. It places that character in $1
because it's contained in a sub-match ()
, invokes the block, which returns $1.upcase
.
As an aside, this is a brain-dead way of capitalizing a string. Even if you didn't know about .capitalize
or this code is from before .capitalize
was available (?), you could still have simply done myString[0] = myString[0].upcase
. The only possible benefit is the .sub
method will work if the string is empty, where ""[0].upcase
will raise an exception. Still, the better way of circumventing that problem is myString[0] = myString[0].upcase if myString.length > 0