Some notes on Peter Cooper's Ruby native extension quickstart

Posted by Tom Copeland Sat, 07 Nov 2009 15:20:00 GMT

In July of 2006 Peter Cooper (author of Beginning Ruby and many helpful web sites) published "How to create a Ruby extension in C in under 5 minutes". This is a nicely formatted little one page tutorial that walks you through creating an extconf.rb and a little test extension that defines a module and a method.

The extension uses rb_define_method to define the method, so it's an instance method on the module. That's why client code has to include the module. If the extension had used rb_define_module_function, it'd be a public class method instead. Then you could invoke it without the include, e.g., with just MyTest::test1 or MyTest.test1. In other words, rb_define_method defines an instance method, while rb_define_module_function define a public class function. It's the difference between:

module MyTest
  def test1
  end
end
and
module MyTest
  def self.test1
  end
end

You could use module_function as well to flip a method from being a private method to a public class method. There's a good section on module definition and visibility in David Flanagan's excellent book The Ruby Programming Language.

In the comment stream Ryan Davis suggests using ruby-inline to save a few more steps. I definitely plan on doing a post on ruby-inline for this blog at some point; neat stuff indeed.