I am running the sample code straight out of Ruby Developer’s Guide,
which shows an example of how Java can call a Ruby interpreter to run
a Ruby script. The code is found on pp.505-506. After downloading
JRuby-0.5.0, however, I get the following exeception:
% java Java2Ruby
Warning: Cannot convert string “Escape,_Key_Cancel” to type
VirtualBinding
Warning: Cannot convert string “Home,_Key_Begin” to type
VirtualBinding
Warning: Cannot convert string “F1,_Key_Help” to type
VirtualBinding
Warning: Cannot convert string “ShiftF10,_Key_Menu” to type
VirtualBinding
Warning: Cannot convert string “F10,Shift_Key_Menu” to type
VirtualBinding
Warning: Cannot convert string “KP_Enter,_Key_Execute” to type
VirtualBinding
Warning: Cannot convert string “AltReturn,Alt_Key_KP_Enter” to
type VirtualBinding
Exception in thread “main” java.lang.ClassCastException:
org.jruby.RubyRange
at org.jruby.javasupport.JavaUtil.convertRubyToJava(JavaUtil.java:163)
at org.jruby.Ruby.evalScript(Ruby.java:203)
at Java2Ruby.main(Java2Ruby.java:33)
Has something changed in JRuby since the book was published? Is there
a now a different way to invoke the Ruby interpreter from KJava?
Below is the source code. Any help would be appreciated. Thanks,
import javax.swing.;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import org.jruby.;
import org.jruby.regexp.;
import org.jruby.javasupport.;
public class Java2Ruby {
public static void main(String[] argv) {
JFrame frame = new JFrame ("Java loves Ruby");
JLabel label = new JLabel ("Cats have 9 lives");
JButton button = new JButton ("Press me");
Ruby ruby = Ruby.getDefaultInstance
(GNURegexpAdapter.class);
button.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog (null,
"Hello from Java\n Responding
button:" +
e.getActionCommand ());
}
});
String rubySource = "listContents = []\n" +
"(1..9).each { |x| listContents << " +
"(\"cat number \" + x.to_s)}\n";
String[] listContents = (String[]) ruby.evalScript
(rubySource,
String[].class);
JList list = new JList (listContents);
frame.getContentPane ().add (button,
BorderLayout.SOUTH);
frame.getContentPane ().add (list,
BorderLayout.CENTER);
frame.getContentPane ().add (label,
BorderLayout.NORTH);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.pack ();
frame.setVisible (true);
}
}