Schism's answer touches on the important points: use snake_case, implicit return, and use
map rather than modifying the string instances in-place with a bang-method (
However, if the string contains many kinds of whitespace - linebreaks, tabs; not just
" " - it may not work as intended.
You could consider using
gsub in order to maintain any and all original whitespace:
This will capitalize words separated by any kind of whitespace, and preserve that whitespace in the resulting string.
The regular expression will match 1 or more consecutive non-whitespace characters (i.e. it'll match individual words), which are then passed to an implicit block that calls
capitalize on the word, replacing it in the string.
input = "here's a STRING with\n\ta newline aNd a tab character"
Here's A String With
A Newline And A Tab Character
(StackExchange's system seems to replace the tab character with 4 spaces, but run the code yourself, and it'll remain a
As for monkey patching the
String class... up to you. I'd consider it for something like this, but I wouldn't do it immediately. The functionality is generic enough that it'd make sense as an addition to
String, but, IMO, the real question is whether its usage is wide-spread enough. If the functionality is only used in a few places, then don't start messing with basic classes.