Simple way to capitalize the first letter of each word in a string using Ruby

I am not infrequently looking to translate a string of either all lowercase or all uppercase characters to a string with the first character of each word capitalized.  I decided to see if I could come up with a quick and easy way to do this in Ruby.  This is what I came up with:


"STRING TO CAPITALIZE".gsub(/b(w+)/) {|x| x.capitalize}
=> "String To Capitalize"
"string to capitalize".gsub(/b(w+)/) {|x| x.capitalize}
=> "String To Capitalize"

It’s not perfect as I think it will choke on quotes but good enough for 5 minutes worth of work.

Leave a Reply

Your email address will not be published. Required fields are marked *