O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required