Ruby - 使用嵌套值优雅地替换哈希值(描述)

时间:2016-06-10 16:37:23

标签: ruby

我正在使用的哈希有一个哈希值,它的值总是包含一个ID,名称和描述。我对保留ID或名称不感兴趣,只想用其相应的描述替换每个哈希值。

代码

hsh['nested']['entries']['addr'] = hsh['nested']['entries']['addr']['description']
hsh['nested']['entries']['port'] = hsh['nested']['entries']['port']['description']
hsh['nested']['entries']['protocol'] = hsh['nested']['entries']['protocol']['description']
hsh['nested']['entries']['type'] = hsh['nested']['entries']['type']['description']
... (many more)

这很好用,但它不是很优雅 - 实际上,我有20个条目/行代码来完成工作。

哈希值的结构(适用于hsh['nested']['entries']['addr']

{ "id" => "27", "name" => "Instance", "description" => "**This is what I need.**" }

将上面第一行代码作为样本,最终结果是hsh['nested']['entries']['addr']的值变为**This is what I need.**

实现这一目标的优雅方式是什么?

2 个答案:

答案 0 :(得分:2)

hsh = { 'nested'=>
        { 'entries'=>
          { 
            'addr'=>{ "id" => "1", "description"=>"addr" },
            'port'=>{ "id" => "2", "description"=>"port" },
            'cats'=>{ "id" => "3", "description"=>"dogs" },
            'type'=>{ "id" => "4", "description"=>"type" }
          }
        }
      }

keys_to_replace = ["addr", "port", "type"]

hsh['nested']['entries'].tap { |h| keys_to_replace.each { |k| h[k]=h[k]["description"] }
  #=> { "addr"=>"addr",
  #     "port"=>"port",
  #     "cats"=>{"id"=>"3", "description"=>"dogs"},
  #     "type"=>"type"
  #   } 

hsh
  #=> {"nested"=>
  #     { "entries"=>
  #       { "addr"=>"addr",
  #         "port"=>"port",
  #         "cats"=>{"id"=>"3", "description"=>"dogs"},
  #         "type"=>"type"
  #       }
  #     } 
  #   }

答案 1 :(得分:1)

sub_hash = hsh['nested']['entries']
categories = %w{addr port protocol type}

categories.each do |category|
  sub_hash[category] = sub_hash[category]['description']
end