Search

Tuesday, November 20, 2007

True object oriented language

 

DSCF2530

Today I was spreading the goodness of Ruby and why I love it so much (and you can expect multiple posts on it). SmallTalk programmers can sneer at me, but hey I wasn't even born when SmallTalk came into being and hence I can be pardoned for pretending that Ruby invented this :)

Languages like Ruby are "truly" object oriented. So even a number like 2 is an instance of the FixNum class. So the following is valid Ruby code which returns the absolute value of the number.

-12345.abs

Taking this to an extreme is the iteration syntax. In C# to write something in a loop "n" time I'd be needed to get into for/foreach syntax, however in Ruby I can do the following

5.times { puts "Hello"}

Which prints Hello 5 times.


However, I actually lied about having to use for/foreach statement in C#. With the new extension-method/lambda goodness we can very well achieve something close in C#.


For that first we create the following extension method

public static class Extensions
{
public static void times(this int n, Action a)
{
for (int i = 0; i < n; i++)
{
a();
}
}
}

Then we can call "times" on an int as easily (well almost as I still need some lambda ugliness).

5.times(() => Console.WriteLine("Hello"));
// Or
6.times(delegate { Console.WriteLine("Hello"); });

1 comment:

Anonymous said...

Well said.