Working With JRuby : JRuby « Scripting « Java






Working With JRuby

 

import java.io.BufferedReader;
import java.io.FileReader;

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

public class MainClass {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();

    ScriptEngine engine = manager.getEngineByName("jruby");

    engine.eval(new BufferedReader(new FileReader("r.rb")));

    Invocable invocable = (Invocable) engine;
    Object tempconverter = invocable.invokeFunction("getTempConverter");

    double degreesCelsius = (Double) invocable.invokeMethod(tempconverter, "f2c", 98.6);
    System.out.println(degreesCelsius);

    double degreesFahrenheit = (Double) invocable.invokeMethod(tempconverter, "c2f",100.0);
    System.out.println(degreesFahrenheit);
  }
}
//////////////
# TempConverter.rb

class TempConverter
  def c2f(degrees)
    degrees*9.0/5.0+32
  end

  def f2c(degrees)
    (degrees-32)*5.0/9.0
  end
end

def getTempConverter
  TempConverter.new
end

 








Related examples in the same category