Learning to Love Ruby

I've started really stepping up my interest / learning in Ruby, and had one of those "this is great!" moments I wanted to share.

At work, we've been pulling some names, etc out of the DB that aren't kept in the correct case, but need to be presented in an eye-pleasing manner to the user.  How do we do this?

Since we're talking about strings, a first check of the string class yields ToUpper(), ToLower(), but no CapitalizetheFirstCharacterAndLowercaseTheRestPlzKThx(), so we will have to keep looking.

Capitalization of names is affected by the culture, so this may be found in System.Globalization.  Sure enough, TextInfo::ToTitleCase() is what we are looking for.

So, there is a little extra work to get the conversion to correct capitalization. I need an instance of TextInfo to pass my text to.  Not too bad, but here we go:

string passCapitalization = "testing";
System.Globalization.TextInfo textInfo = System.Globalization.CultureInfo.CurrentCulture.TextInfo;
Console.WriteLine("{0} converted to title case: {1}", passCapitalization, textInfo.ToTitleCase(passCapitalization));

 

And the output:

TestingDotNet

So, how hard is this to do in Ruby?

TestingRb

Yes, it's easy, but what about for a real business application, where you'd want to capitalize all the words in a sentence?

TestingRbMult

Ruby's capitalize string method won't do it, but TextInfo::ToTitleCase will.

string doubleCapitalization = "double testing";
Console.WriteLine("{0} converted to title case: {1}", doubleCapitalization, textInfo.ToTitleCase(doubleCapitalization));
TestingDotNetMultWords 

Luckily, Ruby is just our language, and Rails is actually our framework. Rails extends the string class with a titlecase method that does just what we need.

TestingRailsMult

The feeling I got when discovering this was that in using the language and framework, doing what I wanted to do was easy and straightforward. It just worked.

As a semi-unrelated aside, I feel ToTitleCase is broken in the .Net Framework.  If the output is supposed to be in title case, why does the format of the input matter?  Why does it do nothing when the input is all caps?

string failCapitalization = "FAILING";
Console.WriteLine("{0} converted to title case: {1}", failCapitalization, textInfo.ToTitleCase(failCapitalization));

TestingDotNetFailing

posted @ Tuesday, August 12, 2008 9:15 PM

Print

Comments on this entry:

No comments posted yet.

Your comment:



 (will not be displayed)


 
 
 
Please add 3 and 7 and type the answer here:
 

Live Comment Preview: