How do you reference a variable added to a ScriptScope from IronRuby?
-
27-10-2019 - |
Pergunta
I'm trying to add a Variable to the scope and then access that variable from my ruby expression.
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();
Ruby
class Person
def initialize(name)
@name = name.capitalize
end
def sayHi
puts "Hello #{@name}!"
end
end
Solução
You were pretty close. Just change the last two lines of your C# code to the next ones:
dynamic p = scope.Engine.Execute("Person.new(name)", scope);
p.sayHi();
In addition, though I'm not sure what you're trying to achieve, you can use your class from C# in an easier fashion:
var engine = Ruby.CreateEngine();
var scope = engine.ExecuteFile(@"C:\codebase\Test\Test2\Test2\person2.rb");
dynamic globalConstants = engine.Runtime.Globals;
dynamic person = globalConstants.Person.@new("shay");
person.sayHi();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow