Created
November 11, 2010 15:53
-
-
Save JoshCheek/672665 to your computer and use it in GitHub Desktop.
Illustrates how I think of Ruby's methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
typedef struct { | |
char* name; | |
int (*pointer)( int arg ); | |
} Method; | |
typedef struct { | |
Method* methods; | |
int methods_size; | |
} Class; | |
typedef struct { | |
Class* class; | |
} Object; | |
int twice( int arg ) { return arg * 2; } | |
int thrice( int arg ) { return arg * 3; } | |
Method* method( Object *o , char* method_name ) { | |
int i; | |
for( i = 0 ; i < o->class->methods_size ; ++i ) | |
if( !strcmp( o->class->methods[i].name , method_name ) ) | |
return &o->class->methods[i]; | |
return NULL; | |
} | |
int main( ) { | |
Method methods[] = { | |
{ "twice" , twice }, | |
{ "thrice" , thrice }, | |
}; | |
Class Multiplier = { | |
methods , | |
sizeof(methods)/sizeof(Method) | |
}; | |
Object multiplier = { &Multiplier }; | |
Method *my_meth = method( &multiplier , "twice" ); | |
printf( "%s: %d\n" , my_meth->name , my_meth->pointer(1) ); | |
my_meth = method( &multiplier , "thrice" ); | |
printf( "%s: %d\n" , my_meth->name , my_meth->pointer(1) ); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment