Yesterday afternoon I decided it's about time I finally learn how to write Ruby C extensions, so I went ahead and rewrote one of our RubyLearning.org exercises in C. Here's the exercise description: Write a class called Person, that has balance as an instance variable and the following public method: show_balance. I shall create the Person object as follows: p = Person.new(40000) puts p.show_balance # calling the method Here's the program in C, with relevant function signatures included as comments: #include static VALUE initialize(VALUE self, VALUE amount) { // VALUE rb_iv_set(VALUE obj, char *name, VALUE value) rb_iv_set(self, "@balance", amount); return self; } static VALUE show_balance(VALUE self) { // VALUE rb_iv_get(VALUE obj, char *name) return rb_iv_get(self, "@balance"); } void Init_person() { // VALUE rb_define_class(char *name, VALUE superclass) VALUE cPerson = rb_define_class("Person", rb_cObject); // void rb_define_method(VALUE classm More
2011-06-25