Question

I have an Ini file, and I am using IniFile to help parse it. I want to add a new section at the top of the ini file, how do I do this?


sample.ini

[Student1]
A = 1

[Student2]
B = 1

My expected result,

[Summary]
NumOfStudents=2

[Student1]
A = 1

[Student2]
B = 1

Problem: the Summary section is always inserted at bottom.

[Student1]
A = 1

[Student2]
B = 1

[Summary]
NumOfStudents=2

My Ruby script

iniFileHandle = IniFile.load(sample.ini)
numOfStudents = iniFileHandle.sections.size

iniFileHandle['Summary'] = {'NumOfStudents' => numOfStudents}

Additional Ruby IniFile 2.0.2 Doc From the doc, I don't find any functions to insert a section at the top.

Was it helpful?

Solution 2

1) Why is the order of the sections in an ini file relevant?

2) my_prog.rb:

require 'inifile'

ini_file = IniFile.load("sample.ini")
numOfStudents = ini_file.sections.size

h = {
  "Summary" => { "NumOfStudents" => numOfStudents }
}

ini_file.instance_eval do
  p @ini                   #instance_eval() changes self to ini_file, and
  h.merge! @ini            #all instance variables are looked up in whatever
  @ini = h                 #object is self.  If you look at the inifile gem's source
end                        #code, the sections of the ini file are stored in a
                           #hash called @ini
ini_file.write

--output:--
$ cat sample.ini
[Student1]
A = 1

[Student2]
B = 1

~/ruby_programs$ ruby my_prog.rb 
{"Student1"=>{"A"=>"1"}, "Student2"=>{"B"=>"1"}}


~/ruby_programs$ cat sample.ini
[Summary]
NumOfStudents = 2

[Student1]
A = 1

[Student2]
B = 1

3) Or you can do it this way:

require 'inifile'

class IniFile
  attr_accessor :ini
end

ini_file = IniFile.load("sample.ini")
numOfStudents = ini_file.sections.size


h = {
  "Summary" => { "NumOfStudents" => numOfStudents }
}

results = h.merge! ini_file.ini
ini_file.ini = results

ini_file.write

OTHER TIPS

The code of this gem is really simple, it is only one file.

It doesn't seems to be possible right now. You can implement this feature if you need it. In his code, basically he keep a section name and a hash with the variables on that section. what the []= method does is to add a new variable to the hash using its []= method. Since ruby 1.9 ruby hashes are ordered, but this method adds on the tail of it. A way to add in the front of the hash is like the following:

 {front_key: "Front value"}.merge(original_hash)

Happy hacking.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top