7

If I take a ruby code

puts "Hello World!"

and rewrite it using the C API of Ruby

#include "ruby.h"

int main() {
  ruby_init();

  rb_funcall(Qnil, rb_intern("puts"), 1, rb_str_new2("Hello World!"));

  ruby_finalize();
  return 0;
}

and compile it, is this a way to compile Ruby code?

If I create a program that uses Ripper to parse the Ruby code and rewrite it as C, can I call it as a "Ruby compiler"? There're some ruby code that can't be rewrited in Ruby in this way? Did someone tried to write this kind of "compiler" before?

Guilherme Bernal
  • 8,183
  • 25
  • 43
  • 1
    Any language can be compiled, just as any language can be interpreted. Some languages (Perl, Python, probably Ruby) would need an interpreter embedded in the compiled program in order to fully support undisciplined use of `eval` and such, but that's more or less what your code is doing. – Chris Lutz May 24 '11 at 00:10

2 Answers2

4

A couple of good articles on this topic:

Also have you heard of Crystal? While not truly Ruby, it looks interesting:

Crystal is a programming language with the following goals:

  • Have the same syntax as Ruby, or at least as similar as possible.
  • Never have to specify the type of a variable or method argument.
  • Be able to call C code by writing bindings to it in Crystal.
  • Have compile-time evaluation and generation of code, to avoid boilerplate code.
  • Compile to efficient native code.

about it on SO: Anybody tried the Crystal Programming Language (machine-code compiled Ruby)?

And another (commercial) project with the same purposes but mainly targeted at embedded development: http://foundry-lang.org/

Community
  • 1
  • 1
Redoman
  • 3,059
  • 3
  • 34
  • 62
1

yes that is "c-ified" ruby code, as it were.

The closest things to "ruby to c" have been http://ruby2cext.rubyforge.org, rubinius with its JIT compiler, and ruby2c

http://betterlogic.com/roger/2009/08/how-to-use-the-ruby2c-gem

Another option would be to write a JIT compiler for 1.9's bytecode, that might speed things up a bit.

Also see the mirah language, which is like static, compile time ruby.

Theoretically it should be possible.

rogerdpack
  • 62,887
  • 36
  • 269
  • 388