Thursday, April 30, 2009

Extension Method to Imitate Times() in Ruby

RubyMy friend and co-worker James is gettin' pretty darned good with Ruby. My experience with Ruby is severely limited. So far, the only thing I've done with it was to implement a "business rules engine" to host a DSL in Iron Ruby.

Today, he showed me a pretty cool method that's built into Ruby called int.times() and I was pretty much instantly jealousified! I decided I had to have one . . . and now I do:
public static void Times(this int times, Action action)
{
for (int i = 0; i < times; i++) action();
}
I through together a few test cases to try it out. I had to make a few determinations though. If you call .Times on a negative number, it loops indefinitely (seemingly). I decided that you should never want to say "do something infinity times." If you do want to do that, you should just have your action call itself at the end of its execution. So, here's the test and the output:
[TestCase(4)]
[TestCase(-6)]
public void test_times_iterator(int times)
{
int i = 0;
times.Times(() =>
{
Console.WriteLine("Index: {0}", i);
i++;
});

Assert.AreEqual(Math.Max(times, 0), i);
}

// Index: 0
// Index: 1
// Index: 2
// Index: 3

No comments:

Post a Comment