📜 ⬆️ ⬇️

Getting Started IronRuby from .net

It took me a while to add Ruby script support to the .net project, and it suddenly turned out that a little helloworld example of this was not so easy to find on the Internet.

What you need:
1) IronRuby

2) Studio, I used 10Rc

Create any project and add to the references all dll contents of the ironRuby \ bin folder from the archive from the site.
Test class:
namespace IronRuby.Test
{
public class IronRubyTest
{
public void Execute()
{
ScriptEngine _rubyEngine;
IronRuby.Runtime.RubyContext _rubyContext;
ScriptRuntime runtime = IronRuby.Ruby.CreateRuntime();
_rubyEngine = runtime.GetEngine( "Ruby" );
ScriptScope _scope = _rubyEngine.CreateScope();
String variable = "Hello" ;
_scope.SetVariable( "variable" , variable);
var result = _rubyEngine.Execute( @" variable + ' World' " , _scope);
}
}
}


* This source code was highlighted with Source Code Highlighter .

Voila, the result is the long awaited Hello World =)
')
Minor speed check:

namespace IronRuby.Test
{
public class SimpleObject
{
public int [] mas;
public int [] getless100()
{
List < int > arr = new List < int >();
for ( int i = 0; i < mas.Length; i++)
{
if (mas[i] < 100) arr.Add(mas[i]);
}
return arr.ToArray();
}
}

public class IronRubyTest
{
public void Execute()
{

SimpleObject obj= new SimpleObject();
obj.mas= new int [50000000];
Random rand = new Random ();
for ( int i = 0; i < obj.mas.Length; i++)
obj.mas[i] = rand.Next(100000);

ScriptRuntime runtime = IronRuby.Ruby.CreateRuntime();
ScriptEngine _rubyEngine = runtime.GetEngine( "Ruby" );
ScriptScope _scope = _rubyEngine.CreateScope();
_scope.SetVariable( "obj" , obj);
DateTime time1 = DateTime .Now;
var result1 = _rubyEngine.Execute( @" mas=[]
(0..obj.mas.size()-1).each do |x|
if obj.mas[x]<100
mas+= [obj.mas[x]]
end
end
m1=mas "
, _scope);
DateTime time2 = DateTime .Now;
var result2 = _rubyEngine.Execute( @" obj.mas.find_all{|elem| elem<100} " , _scope);
DateTime time3 = DateTime .Now;
var result3 = _rubyEngine.Execute( @" obj.getless100() " , _scope);
DateTime time4 = DateTime .Now;
var result4 = obj.getless100();
DateTime time5 = DateTime .Now;
var result5 = obj.mas.Where(x => x < 100).ToArray();
DateTime time6 = DateTime .Now;

}
}
}


* This source code was highlighted with Source Code Highlighter .


The test gave the following results:
time2-time1 01: 46.220
time3-time2 00: 40.602
time4-time3 00: 00.353
time5-time4 00: 00.342
time6-time5 00: 01.046

The result was a bit disappointing; there is no comparison in speed with the c # code; it is better not to do serious calculations in this way.
But on the other hand, scripting languages ​​to .net projects are not attached for such purposes.

Source: https://habr.com/ru/post/90891/


All Articles