views:

1338

answers:

5

How do I read/write an ini file in ruby. I have an ini file that I need to

  1. read
  2. change an entry
  3. write out to a different location

How would I do that in ruby? The documentation on this is bleak.

+1  A: 
file = File.new("your.ini", "r")
  while (line = file.gets)
   puts "#{line}" #additionally make changes
  end
file.close
dirkgently
Can't make changes on a file that's opened with "r" - should be "r+"
Sarah Mei
That's why I am outputting to console -- I don't like reading and writing the same file in one go (and some exercise for the OP) :)
dirkgently
very simple I'm looking for a more abstract way addressing the keys and values not only line by line. something like x=INIfile.new('iniin.ini');x['section','key']='newvalue';x.write("newinifile.txtx")something like this seems more straightforward since I know that i'm working with an in file.
Andrew Redd
This doesn't answer the question at all. File != 'an ini file'.
Vertis
A: 

If I understand correctly,

outFile = File.new('out.ini', 'w')
File.open('in.ini', 'r') do |inFile|
  inFile.each_line do |line|
    # foo is the entry you want to change, baz is its new value.
    outFile.puts(line.sub(/foo=(.*)/, 'foo=baz'))
  end
end
outFile.close

Note that when you use File.open with a block, the file will automatically be closed when the block terminates.

Yaser Sulaiman
+1  A: 

I recently used ruby-inifile. Maybe it's overkill compared to the simple snippets here...

method
it's not overkill if it's the simplest way. I tend to think that a gem designed to handle this specifically would be better. Don't suppose you could post an example?
Andrew Redd
Sure, like this, using Linux .desktop files : http://pastie.org/410612I don't know if it's a gem though.
method
+2  A: 
sc
this code looked appealing, but I could not copy/paste the snippet successfully into an file and run it. any way to correct?
MikeJ
I've split the code to several pieces - looks like there's a bug in site engine. Hope this helps.
sc
A: 

Here's another option: http://rubygems.org/gems/ini

Kevin Dente