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 end11 12 puts "\n"13 14 iniparse = IniParse.open("#{path}/ini_parse.ini")15 puts iniparse["0"].class # --> IniParse::Lines::Section16 iniparse["0"].each do |item|17 puts "#{item.key} = #{item.value}" # IniParse: 打印出来和原ini配置一致18 end19 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 end26 end27 end28 document.lines << iniparse["Config"]29 document.save("#{path}/new_config.ini")
ini_parse.ini内容如下:
1 [0]2 key1 = abc3 oldKey = 1234 key2 = xyz5 newKey = 4566 7 [Config]8 Count = 29 Version = 1.0
上述代码输出结果如下:
View Code
HashnewKey = 456oldKey = 123key2 = xyzkey1 = abcIniParse::Lines::Sectionkey1 = abcoldKey = 123key2 = xyznewKey = 456