craig
craig

Reputation: 26262

Combine the values of two hash keys in an array of hashes

I have an array of hashes:

a = [{"ID"=>"FOO", "Type"=>"Name"}, {"ID"=>"1234", "Type"=>"CID"}]

I'm trying to extract the hash where the Type=='CID', then combine the two values to result in CID=1234.

I can do this in multiple steps:

h = a.find{|x| x['Type']=='CID'}
# => {"ID"=>"1234", "Type"=>"CID"}

"#{h['Type']}=#{h['ID']}"
# => "CID=1234"

Is there a way to do this in a one liner?

Upvotes: 0

Views: 198

Answers (3)

tekuri
tekuri

Reputation: 146

You may try this:

if we are not having multiple values of Type = "CID":

   a.select{|x| x["Type"] == "CID"}.map{|x| x.values_at("Type", "ID")}.join("=")

if we have are having Type="CID"

a.detect{|x| x["Type"]=="CID"}.values_at("Type", "ID").join("=")

If we don't have Type="CID" in above array will throw an error, be cautious.

Need to work in all cases we need to do:

 a.detect{|x| x["Type"]=="CID"}.values_at("Type", "ID").join("=") if a.detect{|x| x["Type"]=="CID"}

Upvotes: 1

Alex Harvey
Alex Harvey

Reputation: 15472

You can do it in one line using:

a.select{|x| x['Type']=='CID'}
  .map{|x| "type=#{x['Type']},id=#{x['ID']}"}[0]

Upvotes: 2

Cary Swoveland
Cary Swoveland

Reputation: 110645

a.find { |h| h["Type"] == "CID" }&.values_at("Type", "ID")&.join("=")
  #=>"CID=1234"

a.find { |h| h["Type"] == "cat" }&.values_at("Type", "ID")&.join("=")
  #=> nil

& is Ruby's safe navigation operator, which made it's debut in Ruby v2.3. I added it to cause nil to be returned if there is no match on h["Type"].

Upvotes: 4

Related Questions