将 Ruby Hash 转换为 YAML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17576472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:04:12  来源:igfitidea点击:

Convert Ruby Hash into YAML

rubyhashyaml

提问by Shail Patel

I need to convert a hash like the one provided below into readable YAML. It looks like I can feed YAML::loada string, but I think I need to convert it first into something like this:

我需要将下面提供的哈希转换为可读的 YAML。看起来我可以输入YAML::load一个字符串,但我想我需要先将它转换成这样的:

hostname1.test.com:
  public: 51
  private: 10

{"hostname1.test.com"=>
   {"public"=>"51", "private"=>"10"},
 "hostname2.test.com"=>
   {"public"=>"192", "private"=>"12"}
}

I'm not sure exactly how to do that conversion into that string effectively though.

不过,我不确定如何有效地将该字符串转换为该字符串。

I looked through the HASH documentation and couldn't find anything for to_yaml. I found it by searching for to_yamlwhich becomes available when you require yaml. I also tried to use the Enumerable method collectbut got confused when I needed to iterate through the value (another hash).

我查看了 HASH 文档,但找不到to_yaml. 我通过搜索to_yaml当您require yaml. 我也尝试使用 Enumerable 方法,collect但是当我需要遍历值(另一个哈希)时感到困惑。

I'm trying to use "Converting hash to string in Ruby" as a reference. My thought was then to feed that into YAML::loadand that would generate the YAML I wanted.

我正在尝试使用“在 Ruby中将哈希转换为字符串”作为参考。我当时的想法是将其输入YAML::load并生成我想要的 YAML。

回答by the Tin Man

Here's how I'd do it:

这是我的做法:

require 'yaml'

HASH_OF_HASHES = {
  "hostname1.test.com"=> {"public"=>"51", "private"=>"10"},
  "hostname2.test.com"=> {"public"=>"192", "private"=>"12"}
}

ARRAY_OF_HASHES = [
  {"hostname1.test.com"=> {"public"=>"51", "private"=>"10"}},
  {"hostname2.test.com"=> {"public"=>"192", "private"=>"12"}}
]

puts HASH_OF_HASHES.to_yaml
puts
puts ARRAY_OF_HASHES.to_yaml

Which outputs:

哪些输出:

---
hostname1.test.com:
  public: '51'
  private: '10'
hostname2.test.com:
  public: '192'
  private: '12'

---
- hostname1.test.com:
    public: '51'
    private: '10'
- hostname2.test.com:
    public: '192'
    private: '12'


The Object class has a to_yaml method. I used that and it generated the YAML file correctly.

Object 类有一个 to_yaml 方法。我使用它并正确生成了 YAML 文件。

No, it doesn't.

不,它没有。

This is from a freshly opened IRB session:

这是来自新开的 IRB 会议:

Object.instance_methods.grep(/to_yaml/)
=> []
require 'yaml'
=> true
Object.instance_methods.grep(/to_yaml/)
=> [:psych_to_yaml, :to_yaml, :to_yaml_properties]

回答by Shail Patel

You can use the to_yamlmethod on a hash for this I believe after you require yaml

你可以to_yaml在散列上使用这个方法,我相信在你之后require yaml