[MacRuby-devel] Accessing Obj-C InstVars from Ruby

Edward Hynes ehynes at dharmagaia.com
Mon Mar 30 09:27:51 PDT 2009


Is there a way to access instance variables defined in an Objective-C  
class from a Ruby extension?  I'm porting some of Apple's example code  
to MacRuby as a learning experience and would like to do so  
incrementally.  Porting the code one class at a time works fine, but  
for some of the larger classes I'd like to port them a few methods at  
a time.  Here's an example of what's happening


--- Example.h ---

    @interface Example : NSObject {
        NSString *instVarA;
        NSString *instVarB;
     }

    - (NSString *)methodA;
    @end


--- Example.m ---

    #import "Example.h"

    @implementation Example
      - (id)init {
        if (self = [super init]) {
          instVarA = @"instVarA";
          instVarB = @"instVarB";
        }
        return self;
      }

      - (NSString *)methodA {
        return instVarA;
      }

    @end


--- Example.rb ---

    class Example
      def methodB
        @instVarB
      end
    end


Then at runtime, when I execute the following...

    example = Example.alloc.init
    puts example.methodA.inspect
    puts example.methodB.inspect


.. I get

    "instVarA"
    nil


How do I access InsVarB from Ruby?

Thanks,
Ed




More information about the MacRuby-devel mailing list