如何在 Ruby 中打印双级哈希



我遇到了这样的哈希

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

如果输出格式不是一个问题,你可以试试漂亮的打印库:

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

你嵌入了数组和哈希。我正在向你展示一种接近它的方法。应该让你开始。

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

祝你好运!

最新更新