Question

I found in the legacy code the following:

"myString".sub(/^(.)/) {$1.upcase} seems very weird. While executing in IRB, I got the same result as "myString".capitalize

Wasn't able to find the documentation... so ended up on SO

Was it helpful?

Solution

Not exactly,

 "myString".capitalize
 #=> "Mystring"

 "myString".sub(/^(.)/) {$1.upcase}
 #=> "MyString"

From the docs for capitalize

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase. Note: case conversion is effective only in ASCII region.

OTHER TIPS

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

Both are not exactly same. sub is used to replace the first occurrence of the pattern specified, whereas gsub does it for all occurrences (that is, it replaces globally).

In your question, regular expression is the first character i.e., $1 and replaces with $1.upcase.

CODE :

"myString".sub(/^(.)/) {$1.upcase}

OUTPUT :

"MyString"

CODE :

"myString".capitalize

OUTPUT :

"Mystring"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top