From: Daniel Berger Date: 2006-10-31T02:10:14+09:00 Subject: Re: Alias singleton method from C Tim Pease wrote: > On 10/30/06, Daniel Berger wrote: > > > > Good question. I'm not sure why this code fails: > > > > #include > > > > static VALUE foo_bar(){ > > return rb_str_new2("hello"); > > } > > > > void Init_foo(){ > > VALUE cFoo, singleton; > > > > cFoo = rb_define_class("Foo", rb_cObject); > > > > rb_define_singleton_method(cFoo, "bar", foo_bar, 0); > > > > singleton = rb_const_get(rb_cObject, rb_intern("Foo")); > > rb_define_alias(singleton, "baz", "bar"); > > } > > > > When I compile and run that it fails with "undefined method `bar' for > > class `Foo'" even though it clearly is defined. I can see in class.c > > that rb_define_alias is just calling rb_alias from eval.c. It looks > > like rb_alias handles singletons differently, but why it's not working > > in the example I provided I'm not sure. > > > > rb_define_alias only works for instance methods. It should work for either singletons or instance methods. If it didn't, then this code wouldn't work: class Foo class << self def bar "hello" end alias baz bar end end p Foo.bar => "hello" p Foo.baz => "hello" The C example I pasted is meant to do what I've done there. Internally rb_define_alias calls rb_alias (in eval.c) which checks to see if klass is a singleton or not. So, in theory, I should be able to do: rb_define_alias(singleton, baz, bar); But obviously I'm doing something wrong - I'm just not sure what. Regards, Dan PS - A rb_define_singleton_alias() would be a handy function. :)