Skip to content

Instantly share code, notes, and snippets.

@ssoper
Created April 8, 2011 14:49
Show Gist options
  • Save ssoper/909988 to your computer and use it in GitHub Desktop.
Save ssoper/909988 to your computer and use it in GitHub Desktop.
Ruby's inject method in Objective-C
// Enumerable.h
#import <Foundation/Foundation.h>
typedef id (^InjectBlock)(id, id);
@interface NSArray (Enumerable)
- (id) inject:(id) initial block:(InjectBlock) block;
@end
// Enumerable.m
#import "Enumerable.h"
@implementation NSArray (Enumerable)
- (id) inject:(id) initial block:(InjectBlock) block {
id memo = initial;
if (!memo)
memo = [self objectAtIndex: 0];
for (id obj in self) {
memo = block(memo, obj);
}
return memo;
}
@end
// main.m
#import "Enumerable.h"
int main(int argc, char *argv[]) {
NSArray *ary = [NSArray arrayWithObjects: @"cat", @"sheep", @"bear", nil];
InjectBlock block = ^ id (id memo, id word) {
return ((NSString *)memo).length > ((NSString *)word).length ? memo : word;
};
id longestWord = [ary inject: nil block: block];
NSLog(@"Longest word %@", longestWord);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment