Ruby vs. C# Smackdown
I recently attended a meeting of the Dallas C# SIG, a group which I hadn't attended in quite some time, because they had Adam Keys come in to talk about Ruby. I don't live under a rock, so I've heard the buzz about Ruby but I hadn't spent much time looking into it because it wasn't immensely relevant to my day to day. That said, this was a great chance to learn so I checked out the meeting and I must admit, I was impressed. I'm hardly a convert but I can understand Adam's point that Ruby "feels" more enjoyable to write for him.
While most things Ruby can do I think C# 3.0 has well in hand, there still some things C# can't do yet. The dynamic augmentation of an instance, not a type, is intriguing to me and certainly powerful. One feature that I thought was interesting, and immediately doable in C# 3.0 was the way Ruby can handle loops. For instance take this Ruby code (syntax errors possible, this is not checked) :
50.Times do
Puts "We Built This City ..."
Puts "We Built This City ..."
Puts "On Rock And Roll"
end
I like this much better than the standard C# syntax of a For loop because it focuses on what is important. Its terse yet clear, and I wanted in C# 3.0 right now, so here it is:
public static class LoopingExtensions
{
public static void Times(this int upperBound, Action<int> action)
{
for (int index = 0; index < upperBound; index++)
action.Invoke(index);
}
}
This results in a very nice piece of C# code, equivalent to our Ruby example above:
50.Times(i => {
Console.WriteLine("We Built This City...");
Console.WriteLine("We Built This City...");
Console.WriteLine("On Rock And Roll");
}
Simply enough to implement, and a great example of using Lambda expressions and extension methods to improve the readability of your code.