首先引入相關DLL:Microsoft.Scripting.dll 和Ruby.dll
然後我們新建一個類:

public class Class1


...{

public ScriptModule test(string path)


...{

SourceUnit unit;


string name = "rubytest1";

unit = new SourceFileUnit(RubyEngine.CurrentEngine,path, name, Encoding.UTF8);

ScriptModule m = unit.CompileToModule();

m.Execute();

return m;

}

}
然後,我們就可以通過,下面的代碼執行RUBY文件的代碼,並查看結果了:

protected void Page_Load(object sender, EventArgs e)


...{

StringBuilder builder = new StringBuilder();

using (StringWriter output = new StringWriter(builder))

...{

TextWriter console_out = Console.Out;

ScriptEnvironment.GetEnvironment().RedirectIO(null, output, null);

try


...{

new Class1().test(@"F:\test.rb");

}

finally


...{

ScriptEnvironment.GetEnvironment().RedirectIO(null, console_out, null);

}

}

string actualOutput = builder.ToString();

Response.Write(actualOutput);

}
比如test.rb:

puts "test"
這個是最簡答的RUBY代碼了,我們也可以結合.Net CLR,比如:

require ''mscorlib''


b = System::Text::StringBuilder.new

b.Append 1

b.Append ''-''

true

puts b.to_string

puts b.length
這反應了IronRuby的特色。
當然,我們也可以在代碼裡執行指定的代碼而不是從文件:


public void test2() ...{

ScriptModule module = ScriptDomainManager.CurrentManager.CreateModule("rubytest2");

module.SetVariable("test", "this is a test");


RubyEngine.CurrentEngine.Execute("puts test", module);


}

protected void Page_Load(object sender, EventArgs e)


...{

StringBuilder builder = new StringBuilder();

using (StringWriter output = new StringWriter(builder))


...{

TextWriter console_out = Console.Out;

ScriptEnvironment.GetEnvironment().RedirectIO(null, output, null);

try


...{

new Class1().test2();

}

finally


...{

ScriptEnvironment.GetEnvironment().RedirectIO(null, console_out, null);

}

}

string actualOutput = builder.ToString();

Response.Write(actualOutput);

}
上面實現了動態建立了一段代碼並且從C#給RUBY代碼賦值,並顯示的過程。
不只是可以輸出結果,我們也可以動態地監視他們:
object val = module.LookupVariable("test");
我們也可以直接來執行表達式:

object x = RubyEngine.CurrentEngine.Evaluate("1 + 1");
或者以一種IRB的交互方式:

object x = RubyEngine.CurrentEngine.ExecuteInteractiveCode("1+1");
好了,就簡單地介紹到這裡,更多更復雜的應用還要等待我們的正式版的推出。