如果我有 Foo::Bar 用 Ruby 编写,并且我想向 Bar 添加一个方法作为 C 扩展。现在,当我像这样在 C 中创建 Foo::Bar 时:
static VALUE Foo;
static VALUE Bar;
static VALUE
print_string(VALUE self, VALUE string) {
printf("%s", StringValuePtr(string));
return Qnil;
}
void Init_foo() {
Foo = rb_define_module("Foo");
Bar = rb_define_class_under(Foo, "Bar", rb_cObject);
rb_define_method(Bar, "print_string", print_string, 1);
}
但问题是:
ruby-1.9.2-p180 :001 > require 'ext/foo' #=> ["Foo"]
ruby-1.9.2-p180 :002 > f = Foo::Bar.new #=> #<Foo::Bar:0x000001046bce48>
ruby-1.9.2-p180 :003 > f.original_ruby_method
NoMethodError: undefined method `original_ruby_method' for #<Foo::Bar:0x000001046bce48>
所以我本质上是在覆盖原来的 Foo::Bar。如何扩展它而不覆盖它?