Windows Vista How to capitalize the first letter of each word in a string. Just FYI

  • Thread starter Thread starter kevpan815's Psychiatrist
  • Start date Start date
K

kevpan815's Psychiatrist

Guest
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"
 
Back
Top