如何在ruby中读取INI文件

And*_*edd 7 ruby configuration

如何在ruby中读/写一个ini文件.我有一个我需要的ini文件

  1. 改变一个条目
  2. 写到不同的位置

我如何在红宝石中做到这一点?关于这方面的文件很惨淡.

met*_*hod 12

我最近使用ruby-inifile.与这里简单的片段相比,这可能是过度杀伤...

  • 如果这是最简单的方法,这并不算过分。我倾向于认为专为处理此问题而设计的 gem 会更好。你不认为你可以发布一个例子吗? (2认同)

cwd*_*cwd 12

使用InIFile Gem

正如@method所说,使用inifile gem.还有一个ini宝石,但我没有使用它.

我发现这里文档这里文档更有帮助,这是gem页面链接到的地方.

没有太多的例子,所以这里有一些代码可以帮助你入门:

示例设置

首先,/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
Run Code Online (Sandbox Code Playgroud)

确保已从命令行运行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"
Run Code Online (Sandbox Code Playgroud)

示例结果

运行该文件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
Run Code Online (Sandbox Code Playgroud)

根据需要修改以满足您的需求.