Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Ruby code in .NET?

Tags:

I'd like to use a RubyGem in my C# application.

I've downloaded IronRuby, but I'm not sure how to get up and running. Their download includes ir.exe, and it includes some DLLs such as IronRuby.dll.

Once IronRuby.dll is referenced in my .NET project, how do I expose the objects and methods of an *.rb file to my C# code?

Thanks very much,

Michael

like image 786
marclar Avatar asked Sep 17 '09 21:09

marclar


1 Answers

This is how you do interop:

Make sure you have refs to IronRuby, IronRuby.Libraries, Microsoft.Scripting and Microsoft.Scripting.Core

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronRuby;
using IronRuby.Builtins;
using IronRuby.Runtime;

namespace ConsoleApplication7 {
    class Program {
        static void Main(string[] args) {
            var runtime = Ruby.CreateRuntime();
            var engine = runtime.GetRubyEngine();

            engine.Execute("def hello; puts 'hello world'; end");

            string s = engine.Execute("hello") as string;
            Console.WriteLine(s);
            // outputs "hello world"

            engine.Execute("class Foo; def bar; puts 'hello from bar'; end; end");
            object o = engine.Execute("Foo.new");
            var operations = engine.CreateOperations();
            string s2 = operations.InvokeMember(o, "bar") as string; 
            Console.WriteLine(s2);
            // outputs "hello from bar"

            Console.ReadKey();


        }
    }
}

Note, Runtime has an ExecuteFile which you can use to execute your file.

To get the Gems going

  1. Make sure you install your gem using igem.exe
  2. you will probably have to set some search paths using Engine.SetSearchPaths
like image 169
Sam Saffron Avatar answered Oct 12 '22 08:10

Sam Saffron