.netからIronRubyを始めましょう

最近、Rubyスクリプトのサポートを.netプロジェクトに添付する必要がありましたが、突然、インターネット上でこのhelloworldの小さな例を見つけるのはそれほど簡単ではないことがわかりました。



必要なもの:

1) IronRuby



2)スタジオ、10Rcを使用しました



プロジェクトを作成し、サイトのアーカイブからironRuby \ binフォルダーのすべてのdllコンテンツを参照に追加します。

テストクラス:

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 .






出来上がり、結果は待望のHello World =)です



小さなパフォーマンスチェック:



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 .








テストの結果は次のとおりです。

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



結果は少しがっかりしました。c#コードでの速度の点では比較がありません;したがって、深刻な計算はしない方が良いです。

しかし、一方で、スクリプト言語はそのような目的のために.netプロジェクトに添付されていません。



All Articles