问题描述
我需要将下面提供的哈希转换为可读的YAML。它看起来像我可以提供 YAML :: load
一个字符串,但我想我需要先将它转换为如下所示:
hostname1.test.com:
public:51
private:10
{hostname1.test.com =>
{public=>51,private=>10},
hostname2.test.com=>
{public=>192,private=>12}
}
我不确定如何有效地转换成该字符串。
我浏览了HASH文档,发现 to_yaml
没有任何内容。我通过搜索 to_yaml
找到它,当 require yaml
时变得可用。我也尝试使用Enumerable方法 collect
,但当我需要遍历值(另一个散列)时会感到困惑。
我试图使用作为参考。然后,我的想法就是将它提供给 YAML :: load
,并且这将生成我想要的YAML。
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
以下输出:
---
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'
不,它没有。
这是来自刚刚打开的IRB会话:
pre $ Object $。 b $ b => []
要求'yaml'
=> true
Object.instance_methods.grep(/ to_yaml /)
=> [:psych_to_yaml,:to_yaml,:to_yaml_properties]
I need to convert a hash like the one provided below into readable YAML. It looks like I can feed YAML::load
a string, but I think I need to convert it first into something like this:
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_yaml
which becomes available when you require yaml
. I also tried to use the Enumerable method collect
but got confused when I needed to iterate through the value (another hash).
I'm trying to use "Converting hash to string in Ruby" as a reference. My thought was then to feed that into YAML::load
and that would generate the YAML I wanted.
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'
No, it doesn't.
This is from a freshly opened IRB session:
Object.instance_methods.grep(/to_yaml/)
=> []
require 'yaml'
=> true
Object.instance_methods.grep(/to_yaml/)
=> [:psych_to_yaml, :to_yaml, :to_yaml_properties]
这篇关于将Ruby Hash转换为YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!