Lojic Technologies

Inline C Code in Ruby

with 2 comments

Did you know you can write C code directly within a Ruby program? I learned that at the Ruby Hoedown here in Raleigh and thought I’d share it for those who aren’t aware of it.

First install the rubyinline gem.

sudo gem install rubyinline

Then code πŸ™‚

require 'rubygems'
require 'inline'

class MyTest
  inline do |builder|
    builder.c "
      long factorial(int max) {
        long result = 1;
        while (max >= 2) {
          result *= max--;
        }
        return result;
      }"
  end
end
t = MyTest.new
puts t.factorial(10)

The first time you run this it will be slower than subsequent runs because the C code will be compiled and cached. Typically you’ll find the generated C code in ~/.ruby_inline

Enjoy,
Brian

Written by Brian Adkins

October 5, 2007 at 12:37 am

Posted in programming

Tagged with , ,

2 Responses

Subscribe to comments with RSS.

  1. Any reason it craps out after 12 factorial?

    joe

    April 24, 2008 at 4:41 pm

  2. Joe, it works fine up through factorial(16) for me, but the reason it eventually fails is because there is a limit to what can be stored in a long int.

    Brian Adkins

    April 26, 2008 at 5:30 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: