Kurt W
Kurt W

Reputation: 351

Ruby - Elegantly replace hash values with nested value (description)

The hash I'm working with has a hash for it's values which always contains an ID, name, and description. I am not interested in keeping the ID or name and just want to replace every hash value with its corresponding description.

Code

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)

This works fine, but it is not very elegant--in reality, I have 20 entries/lines of code to get the job done.

Structure of the hash value (for hsh['nested']['entries']['addr'])

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

Taking the first line of code above as a sample, the end result would be the value of hsh['nested']['entries']['addr'] becomes **This is what I need.**

What is an elegant way to achieve this?

Upvotes: 2

Views: 976

Answers (2)

seph
seph

Reputation: 6076

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

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

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110725

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

Upvotes: 2

Related Questions