Cover by Leonard Richardson, Lucas Carlson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

22.5. Using Java Libraries with JRuby

Credit: Thomas Enebo

Problem

Java offers many class libraries that would be useful to a Ruby programmer; you'd like to use one of those libraries from within Ruby. A Java JDBC database may allow you to connect to a database for which Ruby has no connector. Or perhaps you need to use an obscure Java library that has no Ruby counterpart.

Solution

JRuby provides an alternate implementation of the Ruby programming language that runs atop the Java Virtual Machine. When you interpret a Ruby program with JRuby instead of using the default Ruby interpreter, you can load and use Java classes from within the Ruby code.

The first step to using JRuby is to install it:

  1. Download the latest copy of JRuby (see below for the address).

  2. Unzip the JRuby package into the directory where you'd like to install it.

  3. Add to your PATH environment variable the bin/ subdirectory of your JRuby installation.

  4. Unless you've already installed it, download the Java Runtime Environment from Sun's Java web site and install it. You'll need the JRE version 1.4.x or higher.

Now you can invoke the JRuby interpreter with the jruby command and use it to run Ruby code. Here's a simple example that imports and uses Java's built-in Random class:

	#!/usr/bin/env jruby
	# random.jrb
	require 'java'
	include_class 'java.util.Random'

	r = Random.new(123)
	puts "Some random number #{r.nextInt % 10}"
	r.seed = 456
	puts "Another random number #{r.nextInt % 10}"

Heres a run of this program:

 $ jruby random.jrb ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required