2012-06-14 52 views
0

我遇到這樣的如何在ruby中打印雙層hash?

{"num"=>"219", "id"=>"219", "name"=>"219", "key"=>"", "ps"=>["ˈɑ:bitrəri", "ˈɑrbɪˌtrɛri"], "sent"=>[{"orig"=>"\nHe makes unpredictable, decisions.\n", "trans"=>"\his decision is very hard to understand \n"}, {"orig"=>"\nYou can make an choice.\n", "trans"=>"\n you can chose randomly。\n"}]} 

我只是想打印這個哈希的一部分的哈希值。

我的解決辦法是

key = ['key','ps','sent'] 
key.each{|key| key == 'sent' ? (p server_config["sent"].to_s) : (p server_config[key])} 

它不能很好地工作。 二級哈希打印這樣

[{\"orig\"=>\"\\nAs soon as he kicked the bucket, he started to become famous.\\n\", \"trans\"=>\"\\nhe die and he became famous \\n\"}, ]" 

如何打印此兩級哈希以及

我想就像下面的輸出。

As soon as he kicked the bucket, he started to become famous. 

he die and he became famous. 
+0

什麼不好? –

+0

二級哈希打印這樣的[{\「原稿\」 => \「\\ NAS甫一翹辮子了,他開始成名。\\ñ\」,\「反式\」 => \」 \\ NHE死,他成爲著名的\\ñ\「}]」 – user1396000

+0

你期望的輸出? –

回答

0

如果輸出格式不是constrait你可以試試pretty print庫:

require 'pp' 

[ 'key','ps','sent' ].each do |key| 
    PP.pp(data[key]) 
end 
+0

您好,感謝您的幫助。但是,我只想枚舉這個散列並用幾個鍵(而不是全部鍵)打印它。我不知道這個兩級散列。 – user1396000

0

你有數組和散列嵌入。我向你展示了一種方法來處理它。應該讓你開始。

my_hash = {"num"=>"219", "id"=>"219", "name"=>"219", "key"=>"", "ps"=>["a:bitreri", "arbitreri"], "sent"=>[{"orig"=>"\nHe makes unpredictable, decisions.\n", "trans"=>"\his decision is very hard to understand \n"}, {"orig"=>"\nYou can make an choice.\n", "trans"=>"\n you can chose randomly.\n"}]} 

my_hash["sent"].each{|item| item.each {|key, val| puts val}} 

祝你好運!