Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby collect unique elements

Tags:

ruby

hash

I have some array of hashes

a = [{name:"x", long:1.0, lat:2.0}, 
     {name:"y", long:2.0, lat:3.0}, 
     {name:"z", long:1.0, lat:2.0}]

how to delete {name:"x", long:1.0, lat:2.0}, which coords are equal of last element, Other words I need to leave last (in my case: with name:"z") hash with unique coords and drop all previous element with same coords

like image 425
Vyacheslav Loginov Avatar asked Dec 26 '22 09:12

Vyacheslav Loginov


1 Answers

Try using Array#uniq with a block:

a.uniq { |item| [item[:lat], item[:long]] }

The return value of the block is used as the value to compare for uniqueness.

It's not clear why you want "x" to be deleted and not "z", but you could achieve that with the example data set by reversing the array before calling uniq on it.

like image 189
Jimmy Avatar answered Jan 10 '23 21:01

Jimmy