Monday, March 26, 2007

Capitalizing The First Letter Of Each Word In A String

Say we have a string "This is my String" - we want to capitalize the first letter of each word so that my string becomes "This Is My String". My first attempt was to use the capitalize method -

my_string = "This is a String"
my_string.capitalize --> "This is a string"

Not exactly what we want. Turns out that capitalize converts the *first character* of the string (letter "T" in this case) to upper case and the rest of the letter to lower case. In other words, if

my_string1 = "this is a String",
my_string1.capitalize --> "This is a string"

Notice that "t" in "this" became "T" and "S" in "string" became "s".

In order to capitalize the first letter of each word, we have to split the string into words and then apply capitalize on each word.

my_string.split(” “).each{|word| word.capitalize!}.join(” “) --> "This Is A String"

We used "capitalize!" instead of "capitalize" . The difference is that "capitalize!" capitalizes the word in place whereas "capitalize" returns a copy of the word capitalized.

What if we wanted to capitalize all the letters in the string? Turns out, this is straight-forward:

my_string.upcase! --> "THIS IS A STRING"

4 comments:

Anonymous said...

Hey Bhanu, thanks a lot for this post.

I just used it to create a tiny script that i an use to quickly rename my MP3s so that each word is capitalized and underscores become spaces.

here is the source:



# Script to rename MP3s where the words are delimited by underscores.
# artist_-_song_title => Artist - Song Title

thestring = nil
while thestring != "exit"
print "Enter the song title: "
thestring = gets.chop
puts thestring.split("_").each{|word| word.capitalize!}.join(" ") + "\n"
end

Anonymous said...

Thanks for the tidbid.

Anonymous said...

Rails ActiveSupport extends String with titleize()

"man from the boondocks".titleize # => "Man From The Boondocks"

Anonymous said...

Here's another option.

my_string.gsub(/\w+/) { |s| s.capitalize }