tags:

views:

218

answers:

2
+3  Q: 

require 'rubygems'

I have seen many samples of Ruby code with this line (for example, http://www.sinatrarb.com/). What is purpose of this require?

# require 'rubygems'
require 'sinatra'
get '/hi' do
  "Hello world!"
end

In all cases the code works without this line.

+1  A: 

It is often superfluous. It will allow you to require specific versions of particular gems though, with the gem command.

http://docs.rubygems.org/read/chapter/4

Jakob Kruse
+1  A: 

require 'rubygems' will adjust the Ruby loadpath allowing you to successfully require the gems you installed through rubygems, without getting a LoadError: no such file to load -- sinatra.

From the rubygems-1.3.6 documentation:

When RubyGems is required, Kernel#require is replaced with our own which is capable of loading gems on demand.

When you call require 'x', this is what happens:

  • If the file can be loaded from the existing Ruby loadpath, it is.

  • Otherwise, installed gems are searched for a file that matches. If it's found in gem 'y', that gem is activated (added to the loadpath).

The normal require functionality of returning false if that file has already been loaded is preserved.

See the documentation for Kernel#require to understand why this is necessary.

Carmine Paolino
Btw, I don't recommend it. See this post by Ryan Tomayko: http://gist.github.com/54177
Carmine Paolino
@Carmine Paolino, regarding your comment: Sinatra is a gem. What is the best way to make sure that requiring it does not produce an error without using `require 'rubygems'`?
Yar
In Ruby 1.9 'require "rubygems"' happens automatically. In previous Rubies rubygems is not automatically required and you will get the error. Your best bet is to automatically type it in unless you are sure you are running always in 1.9+. Ruby won't care if you require it twice in 1.9+ and your code will be happy in 1.8.whatever.
Greg
@yar: The post I linked presents 3 solutions.
Carmine Paolino
@Greg: quoting Ryan Tomayko: "The system I use to manage my $LOAD_PATH is not your library/app/tests concern. Whether rubygems is used or not is an environment issue. Your library or app should have no say in the matter. Explicitly requiring rubygems is either not necessary or misguided."
Carmine Paolino
@Carmine Paolino, seems like all of the three solutions require rubygems, just indirectly.
Yar
@yar: in fact they are solutions to the problem (in your own words) "the best way to make sure that requiring it does not produce an error without using `require 'rubygems'`". If you don't use rubygems you just use `Kernel#require` which is quite straightforward...
Carmine Paolino