mercredi 4 mars 2015

Improve performance to find an array of ids from array of hashes in Ruby

Consider a array of hashes



a=[{'id'=>'1','imageUrl'=>'abc'},{'id'=>'2','imageUrl'=>'efg'},{'id'=>'3','imageUrl'=>'hij'}]


Consider an array of characters/numbers/ids



b=['1','2','5']


I would like to match ids of b with a. With all matches, I would like to replace the value of b with the corresponding hash.


In the above example, the values '1' and '2' are common between a and b, so I replace '1' and '2' in b with the corresponding hash values of a.


So the resultant b becomes



b=[[{"id"=>"1", "imageUrl"=>"abc"}], [{"id"=>"2", "imageUrl"=>"efg"}], []]


I wrote the following code:



b.each_with_index{|r,index|
puts index
k=a.select {|z| z["id"]==r }
b[index]=k
}


Is there a better solution? A more sleek one. I am new to ruby.


Aucun commentaire:

Enregistrer un commentaire