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
Tags: c, programming, ruby
-
Any reason it craps out after 12 factorial?

2 comments
Comments feed for this article
Trackback link: http://lojic.com/blog/2007/10/05/inline-c-code-in-ruby/trackback/