High Tech Sorcery

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

by on Mar.18, 2010, under Ruby On Rails

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

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...