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
-
Pat Eyler says:
August 1, 2006 at 6:09 pmI'm pretty sure that C++ is supported out of the box too. ObjC was trivial to add, according to zenspider.
-
zenspider says:
August 1, 2006 at 10:15 pmdon't use require_gem, just plain require will do fine (with 'inline').
-
Peter Cooper says:
August 1, 2006 at 10:41 pmIt'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
-
Ruby’s Unary Operators and How to Redefine Their Functionality
Ruby’s Unary Operators and How to Redefine Their Functionality
-
The Split is Not Enough: Unicode Whitespace Shenigans for Rubyists
The Split is Not Enough: Unicode Whitespace Shenigans for Rubyists
-
The Mega Ruby News and Release Roundup for February 2012
The Mega Ruby News and Release Roundup for February 2012
-
A Lagom Review of O’Reilly’s ‘Sinatra Up and Running’
A Lagom Review of O’Reilly’s ‘Sinatra Up and Running’