Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Wednesday, October 13, 2010

A Java Library Looks Like A JRuby Library

Problem

In the article I wrote, Introduction to JRuby - Bidirectional Communication, I described how to define a class in Java and call it in JRuby. The class written in Java is called by JRuby in a different way to a library written in pure ruby.

For example, assuming now you are making a Ruby library that has a class and a singleton method Hamburger.arrayze. If it's in Ruby you can write a single rb file hamburger.rb and write the following code.

hamburger.rb:

class Hamburger
  def self.arrayze(x)
    ['begin', x, 'end']
  end
end

and call it from another rb file:

require 'hamburger'
p Hamburger.arrayze('hello')
#=> ["begin", "hello", "end"]

You also can implement Hamburger class in pure Java.

Hamburger.java:

class Hamburger {
  static public String[] arrayze(String x) {
    String[] memo = {"begin", x, "end"};
    return memo;
  }
}

Compile it into a jar file.

$ javac Hamburger.java
$ jar cf hamburger.jar Hamburger.class

Then call the library from an rb file.

require 'hamburger.jar'
include_class Java::Hamburger

p Hamburger.arrayze('hello').to_a
#=> ["begin", "hello", "end"]

The result ran on JRuby is exactly same to the previous one, but the code is very different. You cannot delete .jar extension in require method, abbreviate the include_class declaration, or .to_a to convert Java class Object to Ruby Array of String.

Solution 1

First we should not to return a Java object but to return a Ruby array.

No comments:

Post a Comment

Followers