Parsing Ini Files With Ruby

There doesn’t seem a lot of documentation or examples about parsing ini files in Ruby. There are definitely shortcut ways to do it and I could always write my own methods, but why reinvent the wheel when there are gems? So start out by simply installing the inifile gem.

beacon:~ elubow$ sudo gem install inifile
Successfully installed inifile-0.1.0
1 gem installed
Installing ri documentation for inifile-0.1.0...
Installing RDoc documentation for inifile-0.1.0...

The code for the gem is available from github here. Other inifile documentation is available here. The rest of the inifile documentation is a good reference but doesn’t contain any examples.

For some reason (which I don’t understand so please feel free to explain it in the comments if you know), you have to do more than just the standard require statement for this gem. At the top of your Ruby code, add the lines below. Make sure that you replace the directory location with your directory location.

require 'rubygems'
$:.unshift( '/usr/lib64/ruby/gems/1.8/gems/inifile-0.1.0/lib/' )
require 'inifile'

A short example of the ini file that we will be working with:

[foo]
bar = "baz"
dir = "2009-10-05/"
id = 75

To get the id parameter of the ini file assuming you know its in the [foo]section, you can use the code below. Notice the parameter section of the new object instantiator. The reason for this is that ini files are pretty abstract can have a few variations on format. Therefore you can specify the comment style and parameter definition style during object instantiation. My ini files use the ‘=’ to assign parameters

  ini = IniFile.new( options[:conf], :parameter => '=' )
  section = ini[foo]
  id = section['id']

Using the above code the id variable now contains the contents of the id parameter from the ini file.

Posted in Ruby. Tags: , . 2 Comments »
  • trans

    I think your gems setup must have been amiss. require 'inifile' should work fine.

  • http://amillionhosts.com Thomas

    The author of the inifiles posted a sample script: http://pastie.org/410612