How to embed JRuby 1.9 into a Java class

by john on August 20, 2009

It took awhile longer to figure this out than I would have liked, due to no on-line JavaDocs for JRuby (what’s up with that!?).

But here’s how to embed JRuby 1.9 into a Java class:


import org.jruby.Ruby;
import org.jruby.RubyRuntimeAdapter;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.RubyInstanceConfig;
import org.jruby.CompatVersion;

import java.util.ArrayList;

public class JRubyEmbedded {
  public static void main(String[] args) {
    RubyInstanceConfig ric = new RubyInstanceConfig();
    ric.setCompatVersion(CompatVersion.RUBY1_9);
    Ruby ruby = JavaEmbedUtils.initialize(new ArrayList(), ric);
    RubyRuntimeAdapter rra = JavaEmbedUtils.newRuntimeAdapter();

    System.out.println(rra.eval(ruby, "\"Ruby #{RUBY_VERSION}\""));

    JavaEmbedUtils.terminate(ruby);
  }
}

Leave a Comment

Previous post: Evening of Day 4: St. Mary Lodge and Resort, St. Mary, Montana (near Glacier National Park)

Next post: Ruby inherited callback runs before subclass is loaded