使用 InIFile Gem
正如@method所说,使用inifile http://rubygems.org/gems/inifile宝石。还有一个ini http://rubygems.org/gems/ini宝石,但我没用过。
我找到了文档在这里 http://www.ruby-doc.org/gems/docs/i/inifile-2.0.1/IniFile.html比文档在这里 http://rubydoc.info/gems/ini/0.1.1/frames这是宝石页面链接到的地方。
示例不多,因此这里有一些代码可以帮助您入门:
设置示例
首先,创建一个文件/tmp/desktop.ini
包含这些内容:
[Desktop Entry]
Version=1.0
Type=Application
Name=Foo Viewer
Comment=The best viewer for Foo objects available!
TryExec=fooview
Exec=fooview %F
Icon=fooview
确保你已经跑了gem install inifile
从命令行。
示例代码
创建一个文件,例如/tmp/ini-test.rb
包含这些内容:
require 'inifile'
require 'pp'
# read an existing file
file = IniFile.load('/tmp/desktop.ini')
data = file["Desktop Entry"]
#output one property
puts "here is one property:"
puts data["Name"]
# pretty print object
puts "here is the loaded file:"
pp file
# create a new ini file object
new_file = IniFile.new
# set properties
new_file["Desktop Entry"] = {
"Type" => "Application",
"Name" => 'test',
"Exec" => 'command',
}
# pretty print object
puts "here is a object created with new:"
pp new_file
# set file path
new_file.filename = "/tmp/new_ini_file.ini"
# save file
new_file.write()
puts "the new object has been saved as a file to /tmp/new_ini_file.ini"
结果示例
运行该文件ruby /tmp/ini-test.rb
应该产生类似的结果:
here is one property:
Foo Viewer
here is the loaded file:
{ this output hidden for brevity }
here is a object created with new:
#<IniFile:0x007feeec000770
@comment=";#",
@content=nil,
@default="global",
@encoding=nil,
@escape=true,
@filename=nil,
@ini=
{"Desktop Entry"=>
{"Type"=>"Application",
"Name"=>"test",
"Exec"=>"command",
"Icon"=>"icon_filename",
"Comment"=>"comment"}},
@param="=">
the new object has been saved as a file to /tmp/new_ini_file.ini
根据需要进行修改以满足您的需求。