tags:

views:

42

answers:

1

I'm trying to figure out how to retrieve the value stored in the Person class. The problem is just that after I define an instance of the Person class, I don't know how to retrieve it within the IronRuby code because the instance name is in the .NET part.

 /*class Person
        attr_accessor :name

                def initialize(strname)
                    self.name=strname
                end
    end*/

    //We start the DLR, in this case starting the Ruby version


 ScriptEngine engine = IronRuby.Ruby.CreateEngine();
        ScriptScope scope = engine.ExecuteFile("c:\\Users\\ron\\RubymineProjects\\untitled\\person.rb");

    //We get the class type
    object person = engine.Runtime.Globals.GetVariable("Person");

    //We create an instance
    object marcy = engine.Operations.CreateInstance(person, "marcy");
+2  A: 

[EDIT: Just installed VS and IronRuby and tested everything.]

The easiest way I can think of would be to type marcy as dynamic instead of object, and just call the accessor (which if I remember correctly is actually represented as a property on the .NET side):

dynamic marcy = engine.Operations.CreateInstance(person, "marcy");
var name = marcy.name;

If you are not using .NET 4, you will have to go through the "ugly" string-based API:

var name = engine.Operations.InvokeMember(marcy, "name");

BTW: If you do use .NET 4, you can also simplify some of your other code. For example, Globals implements IDynamicObject and provides an implemention of TryGetProperty that emulates Ruby's method_missing, so all in all you could do something like this:

var engine = IronRuby.Ruby.CreateEngine();
engine.ExecuteFile("person.rb");
dynamic globals = engine.Runtime.Globals;
dynamic person = globals.Person;
dynamic marcy = person.@new("marcy"); // why does new have to be a reserved word?
var name = marcy.name;

Notice how you can just "dot into" Globals to get the Person global constant, instead of having to pass it in as a string and you can just call the new method on the Person class (although you unfortunately have to escape it because new is a reserved word, although it would be trivial for the parser to know the difference) to create an instance.

Jörg W Mittag