
RubyInline was a quick hack that I wrote in response to a group member saying "Ingy did his first version [of Perl's Inline.PM] overnight... it can't be that hard!" In fact, it wasn't, for the first version at least. Since then we've extended it so you can do C++ as well as C, to automatically translate base types to/from ruby and C, and more.
RubyInline comes as a gem which you can install by running:
sudo gem install RubyInline
For your convenience here is the RubyInline README.txt.
In, 3.x, RubyInline has the ability to do any language, although I don't support anything but C/C++ out of the box. Here is a basic example of what RubyInline can do:
class MyTest
def factorial(n)
f = 1
n.downto(2) { |x| f *= x }
f
end
inline do |builder|
builder.c "
long factorial_c(int max) {
int i=max, result=1;
while (i >= 2) { result *= i--; }
return result;
}"
end
end
The time for 1 million iterations of factorial and factorial_c is 27 and 7 respectively on my PowerBook (you can run 'make bench' from a RubyInline tarball on your hardware to get numbers for your platform).
The only thing this demo doesn't show is the argument to the inline method which defaults to :C. If you passed in a different language name (as a Symbol), you'd load and use a different builder.
I've made advances to ruby2c on RubyForge that allow me to write 13 lines of code to create Inline::Ruby. Behold:
module Inline
class Ruby < Inline::C
def initialize(mod)
super
end
def optimize(meth)
src = RubyToC.translate(@mod, meth)
@mod.class_eval "alias :#{meth}_slow :#{meth}"
@mod.class_eval "remove_method :#{meth}"
c src
end
end
end
This allows me to do:
require 'inline'
class MyTest
def factorial(n)
f = 1
n.downto(2) { |x| f *= x }
f
end
inline(:Ruby) do |builder|
builder.optimize :factorial
end
end
And it just works.