Running Ruby methods within C# / .NET

The last example might have been a little too trivial, even by my standards. Even I struggled to imagine a scenario where I might ever need to use it. So hopefully this one will be a little bit more interesting and demonstrate something more useful.

Useful, but still just as simple as the previous examples, that is. Again – you’ll need your references from the downloaded IronRuby bin/ folder. And as you’ve come to expect, a very simple ruby script defining a lambda function.

[codesyntax lang=”ruby”]$m = lambda {
a = Array.new
a.push(2, 3)
(4..50).each do
|i|
(2..(Math.sqrt(i).ceil)).each do
|thing|
if (i.divmod(thing)[1] == 0)
a.push i
break
end
end
end
return a
}
[/codesyntax]

From this, we’ll get an array of the prime numbers. The function can then be executed rather nicely from within your .NET code like this:

[codesyntax lang=”csharp]var ruby = Ruby.GetEngine(Ruby.CreateRuntime());
ruby.Execute(@”
$m = lambda {
//.. snip..
return a
}
“);
var rubyContext = Ruby.GetExecutionContext(ruby);
var m = (Proc)rubyContext.GetGlobalVariable(“m”);
var rubyArray = (RubyArray) m.Call();

foreach (var o in rubyArray)
{
Console.Write(string.Format(“{0},”, o));
}
[/codesyntax]

Now we’re really starting to leverage that syntactical beauty of ruby within .NET and jumping (almost) seamlessly between the two. Now, I really should do some demos on something more useful than prime numbers, and perhaps get into one of the big areas of interest of Ruby – testing frameworks. Not tonight though ๐Ÿ™‚

Demo project available as usual:

Tags: , , , , , , ,

Leave a Reply?