Executing complete (Iron)Ruby scripts from within native C# / .NET

Running Ruby code as-is within .NET is almost too simple to even write home about. In fact I almost didn’t, but after I wrote it the solution stared up at me with its big brown eyes, and I couldn’t resist. I’m not totally sure when I’d ever need to use this, but perhaps taking some legacy Ruby scripts where I don’t really care about the results, and still want to run them amongst some other .NET tasks. It might come up in some obscure unit testing one day. You never know.

So, this still serves as an example of how simple it can be to run ruby scripts within .NET. We’ll get to making use of some return values, and running individual methods in the next post.

Following on from the last example, the following ruby script prints all the prime numbers between 1 and 50.

Code block    
state = Numeric.new
print "2,3,"
(4..50).each do
   (2..(Math.sqrt(i).ceil)).each do
      state = 1
      if (i.divmod(thing)[1] == 0)
         state = 0
   print "#{i}\," unless (state == 0)

With the ruby script complete (you can also run this with the ir.exe that ships with IronRuby if you like)… Next start up a new project within Visual Studio, and add some references from your downloaded IronRuby bin folder (IronRuby.dll, IronRuby.Libraries.dll etc…).

You only need a few lines of code to execute your ruby script.

Code block    
using IronRuby;
// ..
var runtime = Ruby.CreateRuntime();

As before, you can download the full example to check it and run for yourself. And also as before, you will also need IronRuby.

Tags: , , , , , , ,

Leave a Reply?