Cover 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

O'Reilly logo

18.2. Installing and Using a Gem

Problem

You want to install a gem, then use the code it provides in your programs.

Solution

You can install the latest version of a gem with the gem install command. This command looks for an uninstalled gem file on your local system; if it can't find one, it calls out to an external source (gems.rubyforge.org, unless you specify otherwise) asking for a gem file. Since gem install changes the system-wide Ruby installation, you'll need to have superuser access to run it.

	$ gem install RedCloth
	Attempting local installation of 'RedCloth'
	Local gem file not found: RedCloth*.gem
	Attempting remote installation of 'RedCloth'
	Successfully installed RedCloth-3.0.4

A gem contains standard Ruby code files, and once you install the gem, you can require those files normally and use the classes and modules they define. However, gems are not installed in the same path as the standard Ruby libraries, so you'll need to tell Ruby to supplement its normal library path with the path to the gems. The simplest way is to require 'rubygems' in any program that uses a gem, before you write any require statements for libraries installed via gems. This is the solution we use throughout this book.

	# This code assumes the "redcloth" gem has been installed, as in the
	# code above.
	require 'redcloth'
	# LoadError: no such file to load -- redcloth

	require ' 
rubygems'
	require 'redcloth'
	parser = RedCloth::CommandParser.new
	# …

For a solution that works across Ruby scripts, you'll need ...

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