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:
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
Thanks for the tidbid.
Rails ActiveSupport extends String with titleize()
"man from the boondocks".titleize # => "Man From The Boondocks"
Here's another option.
my_string.gsub(/\w+/) { |s| s.capitalize }
Post a Comment