0

我遇到这样的哈希

{"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.
4

2 回答 2

0

您嵌入了 Array 和 Hashes。我向您展示了一种处理方法。应该让你开始。

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}}

祝你好运!

于 2012-06-14T13:28:10.153 回答
0

如果输出格式不是一个约束,您可以尝试漂亮的打印库:

require 'pp'

[ 'key','ps','sent' ].each do |key|
  PP.pp(data[key])
end
于 2012-06-14T13:02:12.277 回答