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.
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...
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.
$:.unshift( '/usr/lib64/ruby/gems/1.8/gems/inifile-0.1.0/lib/' )
A short example of the ini file that we will be working with:
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
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.