2011-03-17 21 views
1

我想向範圍添加一個變量,然後從我的ruby表達式訪問該變量。如何引用從IronRuby添加到ScriptScope的變量?

C#

ScriptRuntime runtime = IronRuby.Ruby.CreateRuntime(); 
var scope = runtime.ExecuteFile("C:\\codebase\\Test\\Test2\\Test2\\person2.rb"); 
scope.SetVariable("name", "Scott"); 
dynamic person = scope.Engine.Execute("p = Person.new(name)"); 
person.sayHi(); 

紅寶石

class Person 
    def initialize(name) 
     @name = name.capitalize 
    end 
    def sayHi 
     puts "Hello #{@name}!" 
    end 
end 

回答

4

你是八九不離十。只是你的C#代碼的最後兩行更改爲下一個的:

dynamic p = scope.Engine.Execute("Person.new(name)", scope); 
p.sayHi(); 

另外,雖然我不知道你想實現的,你可以使用從C#類在一個更簡單的方式是什麼:

var engine = Ruby.CreateEngine(); 
var scope = engine.ExecuteFile(@"C:\codebase\Test\Test2\Test2\person2.rb"); 

dynamic globalConstants = engine.Runtime.Globals; 
dynamic person = [email protected]("shay"); 
person.sayHi(); 
+1

我錯誤地認爲,既然您從範圍調用Execute,那麼它將具有所有必需的範圍。 globalConstants的東西也很酷。這是一種更簡潔的方式來打入紅寶石。 – ScArcher2 2011-03-17 14:10:19