How to embed JRuby 1.9 into a Java class by jgn on Thursday, August 20, 2009 in Code

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:

[source language='ruby'] 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); } } [/source]

comments powered by Disqus