Skip to content

Instantly share code, notes, and snippets.

@dsci
Last active December 10, 2015 05:28
Show Gist options
  • Save dsci/4387745 to your computer and use it in GitHub Desktop.
Save dsci/4387745 to your computer and use it in GitHub Desktop.
class AppDelegate
def applicationDidFinishLaunching(a_notification)
foo = FooBar.new
# call Objective-C method from MacRuby which calls a MacRuby method.
foo.getBarFromRuby
# call a second Objective-C method from MacRuby which calls a MacRuby
# method returning a Hash
foo.getBarContentFromRuby
end
end
#import <Foundation/Foundation.h>
@interface FooBar : NSObject
{
// the Ruby class instance. Has to be a "general" data type.
id _rubyInstance;
}
// Constructor that inits a Ruby instance
- (id) init;
// calls Ruby method;
- (void) getBarFromRuby;
// calls another Ruby method which returns a Hash
- (void) getBarContentFromRuby;
@end
#import "FooBar.h"
@implementation FooBar
- (id) init {
self = [super init];
if (self) {
// initialize the Ruby instance from its class.
_rubyInstance = [[NSClassFromString(@"Mixbar") alloc] init];
}
return self;
}
- (void) getBarFromRuby {
NSLog(@"The drink we got from Ruby: %@", [_rubyInstance drink]); // Xcode did not know about #drink.
}
// A Ruby Hash is a NSDictionary in Objective-C.
- (void) getBarContentFromRuby {
NSDictionary *dict = [_rubyInstance content];
for (id key in dict) {
NSLog(@"key: %@, value: %@ \n", key, [dict objectForKey:key]);
}
}
@end
2012-12-27 12:51:35.909 Mix[9880:503] The drink we got from Ruby: Whisky
2012-12-27 12:51:35.919 Mix[9880:503] key: first, value: Brandy, Whisky
2012-12-27 12:51:35.920 Mix[9880:503] key: second, value: Cola
class Mixbar
def drink
"Whisky"
end
def content
# I don't like the new Hash syntax. If you're not using a Symbol as key
# you have to use the rocket arrow. So, why not using them all time?
{:first => "Brandy, Whisky", :second => "Cola"}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment