Skip to content

Instantly share code, notes, and snippets.

@dportabella
Last active August 29, 2015 13:57
Show Gist options
  • Save dportabella/9388448 to your computer and use it in GitHub Desktop.
Save dportabella/9388448 to your computer and use it in GitHub Desktop.
ruby, converting an array of hashes to a hash based on hash key
def hasharray2hash(array, hash_key)
if (!array.kind_of?(Array) || !hash_key.kind_of?(String))
raise 'invalid parameters'
end
array.reduce({}){|cumulate,entry|
if !entry.kind_of?(Hash)
raise 'expecting a hash: ' + entry.to_s
end
key = entry[hash_key]
if key == nil
raise 'the entry ' + entry.to_s + " has not the required key " + hash_key
end
value = Hash[entry.select{|k,v| k != hash_key}]
cumulate[key] = value
cumulate
}
end
servers = [
{ "name" => "server1", "address" => "10.10.10.11", "port" => 8080},
{ "name" => "server2", "address" => "10.10.10.12"}
]
hasharray2hash(servers, 'name')
# => {"server1"=>{"address"=>"10.10.10.11", "port"=>8080}, "server2"=>{"address"=>"10.10.10.12"}}
hasharray2hash(servers, 'address')
# => {"10.10.10.11"=>{"name"=>"server1", "port"=>8080}, "10.10.10.12"=>{"name"=>"server2"}}
hasharray2hash(servers, 'port')
# RuntimeError: the entry {"name"=>"server2", "address"=>"10.10.10.12"} has not the required key port
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment