【原】ruby中使用iniparse解析ini配置文件

ruby中解析ini配置文件有多种方法,比如inifile、iniparse等gem包,inifile解析出来的配置是乱序的,感觉不直观,这里使用iniparse解析,可以解决乱序问题。

 1 require 'rubygems'
 2 require 'iniparse'
 3 require 'inifile'
 4 path = File.dirname(__FILE__)
 5 
 6 inifile = IniFile.load("#{path}/ini_parse.ini")
 7 puts inifile["0"].class         # --> Hash
 8 inifile["0"].each do |k,v|
 9   puts "#{k} = #{v}"            # IniFile: 因为存储的是Hash,打印出来是乱序的
10 end
11 
12 puts "\n"
13 
14 iniparse = IniParse.open("#{path}/ini_parse.ini")
15 puts iniparse["0"].class                  # --> IniParse::Lines::Section
16 iniparse["0"].each do |item|
17   puts "#{item.key} = #{item.value}"      # IniParse: 打印出来和原ini配置一致
18 end
19 
20 # 写配置示例
21 document = IniParse::Generator.gen do |doc|
22   doc.section("0") do |section|
23     iniparse["0"].each do |item|
24       section.option(item.key, item.value)
25     end
26   end
27 end
28 document.lines << iniparse["Config"]
29 document.save("#{path}/new_config.ini")

ini_parse.ini内容如下:

1 [0]
2 key1 = abc
3 oldKey = 123
4 key2 = xyz
5 newKey = 456
6 
7 [Config]
8 Count = 2
9 Version = 1.0

上述代码输出结果如下:

View Code
Hash
newKey = 456
oldKey = 123
key2 = xyz
key1 = abc

IniParse::Lines::Section
key1 = abc
oldKey = 123
key2 = xyz
newKey = 456

 

posted @ 2013-05-12 16:33  阿King2088  阅读(1262)  评论(0编辑  收藏  举报