Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created November 11, 2010 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/672665 to your computer and use it in GitHub Desktop.
Save JoshCheek/672665 to your computer and use it in GitHub Desktop.
Illustrates how I think of Ruby's methods
#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