First of all, for those who may not know, JRuby is an implementation of the Ruby programming language in Java. In addition to being a Ruby interpreter, JRuby also integrates with the Java platform, so you can interact with your existing Java classes from JRuby.
Being implemented in Java, JRuby of course has full support for Unicode. It also supports the Bean Scripting Framework. Supposedly you can run Ruby on Rails with JRuby, although I have not yet tried doing so myself. For more information about JRuby, go to their web site.
For those who’d like to try it, I’ll give you a very simple Swing application. If you are a bit familiar with both Ruby and Java, then you’ll get into JRuby in no time.
1 #! /usr/local/bin/jruby -w 2 3 require 'java' 4 5 include_class 'java.awt.event.ActionListener' 6 include_class 'javax.swing.JButton' 7 include_class 'javax.swing.JFrame' 8 9 class ClickAction < ActionListener 10 def actionPerformed(event) 11 puts "Button got clicked." 12 end 13 end 14 15 class MainWindow < JFrame 16 def initialize 17 super "JRuby/Swing Demo" 18 setDefaultCloseOperation JFrame::EXIT_ON_CLOSE 19 20 button = JButton.new "Click me!" 21 button.addActionListener ClickAction.new 22 add button 23 pack 24 end 25 end 26 27 MainWindow.new.setVisible true
There that should be it. Remember, this is Ruby, so there’s no need to call the file anything special, and no “only one public class per file” restriction.
So how do you run this program? First of all, you need to have JRuby installed, which I assume you have. I installed my copy into
/usr/local/jruby. I then created a symlink from
/usr/local/bin/jruby. That way the JRuby interpreter behaves just like the “normal” Ruby interpreter.
Assuming you have saved your program as
swingtest.rb, installed JRuby and created your symlink, you should just have to do the following:
% chmod +x swingtest.rb
Simple, wasn’t it?
As I was writing this post, I downloaded the latest version of JRuby and the code above no longer runs. It turns out that you can no longer extend an interface. You are affected if you get this error:
% jruby button.rb
button.rb:[13,19]:[326,432]: superclass must be a Class (#) given (TypeError)
Fortunately, it’s very simple to fix. Simply change the ClickAction class to look as follows:
class ClickAction include ActionListener def actionPerformed(event) puts "Button got clicked." end end
Now it should run fine. Still simple.
Update 2007.05.17: fixed the code to work with JRuby-1.0RC2.