Wednesday, 9 December 2015

Java - Call ruby script functions from java code

Sample Program:

Java Code: SampleJsTest .java
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class SampleJsTest {

public static void main(String[] args) throws NoSuchMethodException, ScriptException, IOException {

//create a script engine manager
ScriptEngineManager manager = new ScriptEngineManager();

//create a RubyScript engine
ScriptEngine engine = manager.getEngineByName("ruby");

engine.eval(Files.newBufferedReader(Paths.get("C:\\eclipse\\RubyDemoProject\\Test.rb"), StandardCharsets.UTF_8));

Invocable inv = (Invocable)engine;
long a = (long) inv.invokeFunction("add", "3", "2");



Ruby script: Test.rb
def add (var1, var2)
   return var1.to_i + var2.to_i

Test.rb - ruby file.

Execute the java program.

Place jruby.jar in build path, to avoid the run time exception.

Download jruby.jar from

Extract the downloaded zip file.

Now set the java build path for 'jruby.jar'.

Now execute the java program again, after setting the build path for 'jruby.jar'.

- For executing the ruby script function from java code using above procedure, doesn't require ruby software installed on your machine.
- Using above procedure java code passes two int values to the ruby script function, but result is returned as long value.


  1. Nice blog regarding use of Java programming codes to make various functions. This is one of the best work of the blogger. I like it very much.

  2. I like your blog a lot. Its informative and full of information. Thank you for sharing.
    Melbourne Mobile Developer