1

I'm trying to use the XmlSimple gem in a script. My script looks like this:

#!/usr/bin/env ruby

gem 'xml-simple', '1.1.5'

xml = XmlSimple.xml_in('test_data.xml')

puts xml

This fails with the error:

./script.rb:5:in `<main>': uninitialized constant XmlSimple (NameError)

Why am I getting this error, and how do I fix it?


These common solutions to similar problems with gems haven't helped me:

  • This error will come up if one forgets to explicitly include the relevant gem. As you can see from my MVCE, I have not made this mistake.
  • Sometimes, explicitly requiring the correct version of the gem solves this problem. However, I am already requiring the most recent version of this gem. I have also double-checked that this is the version of the gem I have installed on my system.
  • According to the XmlSimple documentation, the XmlSimple class should most certainly be defined when this gem is included. I'm not trying to use a class that doesn't exist.
Kevin
  • 14,655
  • 24
  • 74
  • 124
  • By using `gem unpack` to copy the gem's source to my script's directory, I was able to get my script to work. But I'm still confused as to why trying to include the gem the typical way didn't work - including the gem's source directly is definitely a work-around, and I still have some strange problem. – Kevin Aug 18 '16 at 02:11

1 Answers1

3

You have activated the gem, by using the gem method, but you haven’t required it. This means the gem’s files are now on your load path, but they haven’t been loaded by the Ruby interpreter, so their contents aren’t available to your program.

You simply need to add

require 'xmlsimple'

after the gem line.

You don’t always need the gem method, you can just use require and the latest installed version of the gem will automatically be activated — but if you want to specify which version to use you need to use gem explicitly.

matt
  • 78,533
  • 8
  • 163
  • 197