Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Write C code inline with your Ruby code

By Peter Cooper / June 7, 2006

Ruby Inline is an analog to Perl's Inline::C. Out of the box, it allows you to embed C/++ external module code in your ruby script directly. By writing simple builder classes, you can teach how to cope with new languages (fortran, perl, whatever).

I downloaded it (simply download the gem and install it) and tapped out the following code, and it worked just great:

require 'rubygems'
require_gem 'RubyInline'

class << self
	inline do |builder|
		builder.c "
			int dummy(int input) {
				int i = 1;
				while (input >= 1) { input--; i *= 2; }
				return i;
			}
		"
	end
end

puts dummy(8)

This works a treat on OS X. Linux should be fine, but on Windows I can't imagine it running unless you're under Cygwin and have gcc handy. Just watch out for creating infinite loops, because you will need kill -9.

Supposedly Ruby Inline also has support for languages other than C, although C is the only one to work 'out of the box'.

Comments

  1. Pat Eyler says:

    I'm pretty sure that C++ is supported out of the box too. ObjC was trivial to add, according to zenspider.

  2. zenspider says:

    don't use require_gem, just plain require will do fine (with 'inline').

  3. Peter Cooper says:

    It's a habit I picked up ages ago when I had a really crappy installation that wouldn't work without it, sorry :)

Other Posts to Enjoy

Twitter Mentions