Robert Klemme
7/8/2005 8:31:00 AM
Jason Foreman wrote:
> On 7/7/05, Paulo Jabardo <pjabardo@yahoo.com.br> wrote:
>> I was playing around with modules when I noticed that
>> I counld, for example include Math and use sin,cos,etc
>> as if it were a common method. When I tried to do the
>> same in irb
>>
>> module Test
>> def Test.triple(x)
>> 3*x
>> end
>> end
>>
>> Test.triple 2 => 6
>>
>> If I include Test from the toplevel
>> inlcude Test
>>
>> and then call triple directly I get an error:
>> irb(main):005:0> triple 2
>> NoMethodError: undefined method `triple' for
>> main:Object
>> from (irb):5
>>
>>
>> I then tried to implement the same module as an
>> extension:
>>
>> #include <ruby.h>
>>
>> static VALUE triple(VALUE self, VALUE x){
>> return rb_float_new(3.0*NUM2DBL(x));
>> }
>>
>> VALUE modulo;
>>
>> void Init_TestC(){
>> modulo = rb_define_module("TestC");
>> rb_define_module_function(modulo, "triple", triple,
>> 1);
>> }
>>
>> When I load this extension,
>> require 'TestC.so'
>>
>> TestC.triple 2 => 6
>>
>> include TestC
>> triple 2 => 6 # No error
>>
>> I haven't seen this documented. Can I get this same
>> behaviour from ruby code or do I need to write an
>> extension?
>>
>
>
> You ruby module and extension module are not equivalent. Try instead
> this:
>
> module Test
> def triple(x)
> 3*x
> end
> module_function :triple
> end
>
> Test.triple 2 # => 6
>
> include Test
> triple 2 # => 6
It's even simpler:
module Test
def triple(x)
3*x
end
end
>> extend Test
=> main
>> triple 2
=> 6
Kind regards
robert