Ruby - Merge two hashes with no like keys based on matching value -


i find efficient way merge 2 hashes , resulting hash must contain original data and new key/value pair based on criteria below. there no keys in common between 2 hashes, key in 1 hash matches value of key in adjacent hash.

also note second hash array of hashes.

i working relatively large data set, looking efficient solution hoping keep code readable @ same time since end in production.

here structure of data:

# hash hsh1 = { "devicename1"=>"active", "devicename2"=>"passive", "devicename3"=>"passive" }  # array of hashes hsh2 = [ { "host" => "devicename3", "secure" => true  },          { "host" => "devicename2", "secure" => true  },          { "host" => "devicename1", "secure" => false } ] 

here need accomplish:

i need merge data hsh1 hsh2 keeping of original key/value pairs in hsh2 , adding new key called activation_status using the data in hsh1.

the resulting hsh2 follows:

hsh2 = [{ "host"=>"devicename3", "secure"=>true,  "activation_status"=>"passive" },         { "host"=>"devicename2", "secure"=>true,  "activation_status"=>"passive" },         { "host"=>"devicename1", "secure"=>false, "activation_status"=>"active"  }] 

this may answered on stackoverflow looked time , couldn't find match. apologies in advance if duplicate.

i suggest along lines of:

hash3 = hash2.map |nestling|   host = nestling["host"]   status = hash1[host]   nestling["activation_status"] = status   nestling end 

which of course can shrink down bit. version uses less variables , in-place edit of hash2:

hash2.each |nestling|   nestling["activation_status"] = hash1[nestling["host"]] end 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo