Wednesday, April 29, 2009

jirb: Gentle Introduction to JRuby

If you haven't had the opportunity to work with Ruby or JRuby, the jirb tool provides an easy approach to playing with JRuby basic syntax and features.

In the article Accessorize Oracle Database with Ruby, I used screen shots of IRB (Interactive Ruby) to introduce Ruby for scripting. JIRB is the equivalent tool running on JRuby. In fact, in this blog post I will use the same examples in JIRB that I used in that OTN article with IRB to demonstrate Ruby on the JVM with JRuby.

In the OTN article (Figure 3), I demonstrated accessing Ruby predefined constants RUBY_PLATFORM, RUBY_VERSION, and RUBY_RELEASE_DATE in IRB. The next screen snapshot shows the same constants in JIRB along with an additional JRuby-specific constant JRUBY_VERSION.



The fact that the RUBY_PLATFORM constant is set to "java" provides a good clue about this actually being JRuby, but the existence of the JRUBY_VERSION constant (1.2) confirms that it is JRuby 1.2 being used.

I used the first figure (Figure 1) of the OTN Ruby article to demonstrate using Ruby mathematical operators in IRB. The next screen snapshot demonstrates the same mathematical operators in JIRB.



Figure 2 of the OTN article on Ruby demonstrated Ruby String functions in IRB. The next screen snapshot shows these same String functions in JIRB.



Finally, in the Figure 4 of the OTN article on Ruby, I demonstrated (as best as can be done in a static article) how clicking on tab twice brings up completion information in IRB. The same feature works in JIRB:



Besides demonstrating the tab-tab completion functionality of JIRB, this also demonstrates that even an integer (0) is an object in Ruby.


Getting Started with JRuby and JIRB

JRuby can be downloaded here. There are source and binary (jruby-bin-1.2.0.zip) downloads available. When the binary download is complete, it can be unzipped or opened into a directory of choice (such as C:\jruby-1.2.0 in my case. I like to set an environment variable JRUBY_HOME to point to this directory and then place %JRUBY_HOME%\bin on the Path. You can confirm correct setup by entering "jruby -v" on the console. If you see a JRuby version (such as 1.2) and a Ruby version (such as 1.8.6), the setup is correct. Running JIRB is as easy as typing "jirb" at the console prompt.

No comments: