将内容从Ruby中的给定哈希写入yml文件

时间:2017-01-03 11:04:42

标签: ruby file yaml

我有一个yml文件,其中包含有关数据库设置的一些信息。我需要创建一个获取密钥内容并创建文件的文件。

喜欢,我的yml文件:

db_info.yml

databases:
  database1: # This would be first database
    development:
      adapter: mysql2
      host: localhost
      database: dev1
      password: root
      username: root
      encoding: utf8
    test:
      adapter: mysql2
      host: localhost
      database: dev1_test
      username: root
      password: root
      host: localhost
  database2: # This would be second database
    development:
      adapter: mysql2
      host: localhost
      encoding: utf8
      database: dev
      password: root
      username: root
    test:
      adapter: mysql2
      host: localhost
      database: dev_test
      username: root
      password: root
      host: localhost

当我加载此yml文件并尝试在新的yml文件中写入以错误方式保存的单个文件信息。

我想在新文件中写内容,如

new_file.yml

config_file = Rails.root.join('config', 'multiple_database.yml')
file = YAML.load(ERB.new(File.new(config_file).read).result)

file['databases']['database1']所以请回复我哈希

{"development"=>{"adapter"=>"mysql2", "host"=>"localhost", "database"=>"dev1", "password"=>"root", "username"=>"root", "encoding"=>"utf8"}, "test"=>{"adapter"=>"mysql2", "host"=>"localhost", "database"=>"dev1_test", "password"=>"root", "username"=>"root", "encoding"=>"utf8"}}

所以我想在新的yml文件中写这个内容,比如

development:
  adapter: mysql2
  host: localhost
  database: dev1
  password: root
  username: root
test:
  adapter: mysql2
  host: localhost
  database: dev1_test
  username: root
  password: root
  host: localhost

我试过这样的话:

array_of_hashes = [{:"client-1.domaine.net"=>"www.client-1.domaine.net/index.html/xxxxxx", :fef => 12}]
File.open("lib/yamlfile.yml","w") do |file|
   file.write array_of_hashes.to_yaml
end

所以像这样输出

---
- :client-1.domaine.net: www.client-1.domaine.net/index.html/xxxxxx
  :fef: 12

1 个答案:

答案 0 :(得分:0)

尝试应用方法' to_yaml'哈希而不是哈希数组。你会做对的

这是你的代码

array_of_hashes = [{:"client-1.domaine.net"=>"www.client-1.domaine.net/index.html/xxxxxx", :fef => 12}]
File.open("lib/yamlfile.yml","w") do |file|
    file.write array_of_hashes.to_yaml
end

这样做

array_of_hashes = [{:"client-1.domaine.net"=>"www.client-1.domaine.net/index.html/xxxxxx", :fef => 12}]
File.open("lib/yamlfile.yml","w") do |file|
    file.write array_of_hashes[0].to_yaml
                              ^^^
end

并检查。 希望它有所帮助