Ruby require error in loading gems

Long time that I coded in Ruby so thought lets replenish the love.

I started reading Graph APIs from Facebook to get some idea of what capabilities they provide with. Graph APIs are immensely powerful in the kind of data they allow developers to access. No doubt how such powerful ecosystem got created. Graph API responses are in JSON (Javascript Object Notation). I have little familiarity with this representation of data. Coming from old school I’ve mostly played with XML data. So I thought lets first try practicing JSON on Ruby. So first step –

$ gem install json

It was easily installed.

Then I wrote the script to load JSON gem in my script i.e.

require ‘json’

and just to test if this is fine I executed it (being almost sure that it will and I will move on). Ruby interpreter yelled!

$ ruby temp.rb
temp.rb:1:in `require’: no such file to load — json (LoadError)
from temp.rb:1

Hmm. so again. Some googling helped (and refreshed some memory) –

There are three ways to handle this –

1. Put following line to the starting of the script

require ‘rubygems’

2. Execute it as:

$ ruby -rubygems script.rb

3. Add rubygems to RUBYOPT

$ export RUBYOPT=”rubygems”

Well, just now I read this article on Github and it clearly says:

You should never do this in a source file included with your library,
app, or tests:

require ‘rubygems’

Why You Shouldn’t Force Rubygems On People!

So guys, (2) and (3) are the way to go and (1) is to be avoided if you plan to share your Ruby script.