Last active
August 29, 2015 13:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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