Ruby gems in stand-alone ruby scripts

You should be able to simply require it directly in recent versions of Ruby.

# optional, also allows you to specify version
gem 'chronic', '~>0.6'

# just require and use it
require 'chronic'
puts Chronic::VERSION  # yields "0.6.7" for me

If you are still on Ruby 1.8 (which does not require RubyGems by default), you will have to explicitly put this line above your attempt to load the gem:

require 'rubygems'

Alternatively, you can invoke the Ruby interpreter with the flag -rubygems which will have the same effect.

See also:

  • http://docs.rubygems.org/read/chapter/3#page70
  • http://docs.rubygems.org/read/chapter/4

You could use something like this. It will install the gem if it's not already installed:

def load_gem(name, version=nil)
  # needed if your ruby version is less than 1.9
  require 'rubygems'

  begin
    gem name, version
  rescue LoadError
    version = "--version '#{version}'" unless version.nil?
    system("gem install #{name} #{version}")
    Gem.clear_paths
    retry
  end

  require name
end

load_gem 'your_gem'