Ruby Extensions: A Brief Tutorial

November 3, 2011 • 0 comments

The Ruby ruby

Ruby is slow, compared to C. But if you write the critical parts of your program in C, you can have Ruby’s rapid development AND C’s runtime speed! Profile your program, and use the steps below to port the slowest inner loops to C!

  1. Download the skeleton of your extension (or look at it on Github). Unzip it into an empty folder.
  2. Read build.sh, which is a short bash script that shows you how to build your extension.
  3. Read extconf.rb, which is the extension configuration script.
  4. The datatype ‘VALUE’ represents EVERYTHING in Ruby. You’ll need to decode your data in order to work with it in C, and re-encode everything in order to return it to Ruby.
  5. When you call a C function from Ruby, the first argument is the receiver of the method, a VALUE called self. Basically, if you want a two-argument Ruby function, you’ll need three arguments in the C version of it.
  6. Read yourextension.c. It outlines the main steps in a simple Ruby extension.
  7. If you want to know more about how extensions work under the hood, or if something isn’t abundantly clear from the file, read the ruby-docs!

Leave a Reply

Your email address will not be published. Required fields are marked *