Archives page

Posts Tagged ‘vistasquad’

Using C# / .NET libraries within IronRuby

I attended my first VistaSquad meeting on Wednesday. Part of the evening was a very interesting talk from @ben_hall on IronRuby, which among many other things included how to use any .NET CLR libraries direct from your IronRuby script (running via the .NET DLR).

Whilst my example below is extremely trivial, it shows how you might make use of any existing libraries within your Ruby scripts. This same technique applies to any .NET libraries, whether they’re custom, part of the framework, or created by your gran. I don’t think I really need to sell it in – but I love the flexibility that this provides.

So to get to the example, this simple piece of C# displays all the prime numbers between 0 and maxNumber:

[codesyntax lang=”csharp”]public int[] DisplayPrimeNumbers(int maxNumber)
{
int max = maxNumber;
List previousPrimes = new List();
previousPrimes.Add(2);
if (max < 2) return null; // none for (int i = 3; i <= max; i++) { int maxDivisor = (int)Math.Floor(Math.Sqrt(i)); bool foundDivisor = false; for (int j = 0; j < previousPrimes.Count; j++) { if (previousPrimes[j] > maxDivisor) break;
if ((i % previousPrimes[j]) == 0)
{
foundDivisor = true;
}
}
if (!foundDivisor)
{
previousPrimes.Add(i);
}
}
return previousPrimes.ToArray();
}
[/codesyntax]

We can build that up into a class library and using IronRuby, manipulate the return of the method the same as though we had been running native ruby.

[codesyntax lang=”ruby”]require ‘mscorlib’
require ‘CSharpLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’;

prime_numbers = CSharpLib::PrimeNumbers.new

(prime_numbers.DisplayPrimeNumbers 20).each do |num|
puts num
end
[/codesyntax]

You can download the full sample below, a C# console app is also included for completeness (although isn’t a part of the IronRuby process). You will of course, need to download IronRuby first, and add the installed bin/ folder to your path. Then just change to the <sample>/ruby/ directory, and run it with:

ir run.rb

It’s probably worth noting that IronRuby is still a way off from a 1.0 release, but it’s already very usable and looking rather cool. Since it’s on my recent //TODO list, I’ll be doing a few more examples here – next time turning this one its head and executing your ruby scripts from within C#. In the meantime, you can check out Ben’s set of slides from Wednesday on Slideshare.