Java Programming – How to Execute a Ruby File in Java and Call Functions

javaprogramming-languagesruby

I do not fully understand what am I asking (lol!), well, in the sense of if it is even possible, that is. If it isn't, sorry.

Suppose I have a Java program. It has a Main and a JavaCalculator class. JavaCalculator has some basic functions like

public int sum(int a,int b) {
   return a + b
}

Now suppose I have a ruby file. Called MyProgram.rb.

MyProgram.rb may contain anything you could expect from a ruby program. Let us assume it contains the following:

class RubyMain
  def initialize
    print "The sum of 5 with 3 is #{sum(5,3)}"
  end
  def sum(a,b)
    # <---------- Something will happen here
  end
end

rubyMain = RubyMain.new

Good. Now then, you might already suspect what I want to do:

  • I want to run my Java program
    • I want it to execute the Ruby file MyProgram.rb
    • When the Ruby program executes, it will create an instance of JavaCalculator, execute the sum function it has, get the value, and then print it.
    • The ruby file has been executed successfully.
  • The Java program closes.

Note: The "create an instance of JavaCalculator" is not entirely necessary. I would be satisfied with just running a sum function from, say, the Main class.

My question: is such possible? Can I run a Java program which internally executes a Ruby file which is capable of commanding the Java program to do certain things and get results? In the above example, the Ruby file asks the Java program to do a sum for it and give the result.


This may sound ridiculous. I am new in this kind of thing (if it is possible, that is).

WHY AM I ASKING THIS?

I have a Java program, which is some kind of game engine. However, my target audience is a bunch of Ruby coders. I don't want to have them learn Java at all. So I figured that perhaps the Java program could simply offer the functionality (capacity to create windows, display sprites, play sounds…) and then, my audience can simply code with Ruby the logic, which basically justs asks my Java engine to do things like displaying sprites or playing sounds.

That's when I though about asking this.

Best Answer

What you're probably really after is JRuby --> http://jruby.org/

JRuby is a fully featured, compliant Ruby implementation on the Java Virtual Machine. According to some Rubyists, it also happens to be the fastest (assuming you're running on a Java 7 compatible VM). JRuby can call into Java libraries and take return values from those calls, in short you can have the best of both worlds.

Related Topic