简体   繁体   中英

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?

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"] .

You can do it in one line using:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM