Capitalize the first character of multi word string
The following sample of code capitalizes the first character of every word in a string.
And you can do the ruby string capitalization in this way (from David Felstead)
The following sample of code capitalizes the first character of every word in a string.
And you can do the ruby string capitalization in this way (from David Felstead)
RSS feed for comments on this post · TrackBack URI
David Felstead said,
May 5, 2007 @ 5:14 pm
This will actually modify the string, so if you had (substituting _ for spaces) “hello___how___are___you” would be replaced with “Hello_How_Are_You”, i.e. the spaces are removed.
This might be a better solution:
str.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
admin said,
May 5, 2007 @ 7:32 pm
Thanks for the comment David.
Actually, the string will be modified, it will just out put a new string with upper case words.
However, I like your solution more, ill add it to the post!
pvh said,
August 28, 2007 @ 1:36 pm
Just to clarify David’s post, the error in your original function is that it modifies whitespace. It will replace all whitespace with a single space, including tabs or multiple spaces. Thus the string “Hello world!” will become “Hello World!” using your original function.
pvh said,
August 28, 2007 @ 1:38 pm
How appropriate, the blog ate my whitespace! My example should look like: “Hello____________________world” becoming “Hello_world”.
Robert B. said,
October 11, 2007 @ 8:27 am
Preseneted solution with regular expression doesn’t take into consideration string with national characters, i.e. not from regular a-z range.
rajat said,
November 15, 2007 @ 12:52 am
Very useful,
thanks
Yavor Ivanov said,
May 14, 2008 @ 11:34 am
Hey it’s very simple for national characters as well.
If you have problems with local chars just always put the string through chars.
In this case it is simply:
str.chars.upcase.to_s
Greetings from Bulgaria!