Tuesday, May 12, 2009

Extension Method to Imitate Upto() in Ruby

RubyLast month, I wrote a blog post about using an extension method to imitate the ruby method times(). I recently found another cool method in ruby that I wanted to avail to the C# public.

Now, before I show you the implementation, I'll just say that it doesn't do anything the for loop wouldn't do on its own. I think the method has two benefits. One, I think it looks clean because it's basically a fluent way to create a for loop. Two, I like the fact that you can pass an action to the method.

In Ruby, the implementation looks like this:
5.upto(10){ |i| puts i; }

# output
# 5
# 6
# 7
# 8
# 9
# 10
I added the following extension method to one of my utility extension method libraries:
public static void UpTo(this int start, int upto, Action<int> action)
{
for (int i = start; i <= upto; i++) action(i);
}
Here are the test cases and the results:
[TestCase(4, 12)]
[TestCase(-10, 10)]
[TestCase(10, 5)]
public void test_upto_iterator(int from, int upto)
{
int test = 0;
from.UpTo(upto, num =>
{
Console.WriteLine("Index: {0}", num);
test += num;
}
);

int expected = 0;
for (int i = from; i <= upto; i++)
expected += i;

Assert.AreEqual(expected, test);
}

// ***** ESG.Utilities.System.Tests.IntegerExtensionTests.test_upto_iterator(-3,2)
// Index: -3
// Index: -2
// Index: -1
// Index: 0
// Index: 1
// Index: 2

// ***** ESG.Utilities.System.Tests.IntegerExtensionTests.test_upto_iterator(4,8)
// Index: 4
// Index: 5
// Index: 6
// Index: 7
// Index: 8

No comments:

Post a Comment