Rubies collect unique elements

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 remove {name:"x", long:1.0, lat:2.0}

which coordinates are equal to the last element. Other words that I need to leave in the past (in my case: c name:"z"

) a hash with unique coordinates and remove all previous elements with the same coordinates

+3


source to share


1 answer


Try using Array#uniq

with a block:

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

      



The return value of the block is used as a comparison value for uniqueness.

It's not clear why you want to remove "x" and not "z", but you can achieve this with a dataset by reversing the array before calling uniq

on it.

+7


source







All Articles