How to execute a Ruby file in Java, capable of calling functions from the Java program and receiving primitive-type results?

Posted by Omega on Programmers See other posts from Programmers or by Omega
Published on 2012-12-20T07:30:36Z Indexed on 2012/12/20 11:12 UTC
Read the original article Hit count: 267

Filed under:
|
|

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.

© Programmers or respective owner

Related posts about java

Related posts about programming-languages