JavaからRubyを呼んで、戻り値を取得する
evalScriptletの戻り値を使えば良かったらしい。そのまんまじゃん。
import org.jruby.Ruby; import org.jruby.runtime.builtin.IRubyObject; public class CallRuby { public static void main(String[] args) throws Exception { Ruby runtime = Ruby.newInstance(); // Kernelモジュールにtestメソッド(文字列'hoge'を返す)を追加 String scriptlet = "module Kernel\n def test\n 'hoge'\n end\nend\n"; runtime.evalScriptlet(scriptlet); // testメソッドを呼んで、戻り値を取得する IRubyObject obj = runtime.evalScriptlet("test"); System.out.println(obj.getClass().getName()); System.out.println(obj); } }
結果はこう。
org.jruby.RubyString hoge
RubyString型で、文字列"hoge"が返されていることが分かります。