Caleb Sayre Caleb Sayre - 2 months ago 20
Ruby Question

How to use .uniq with hashes for unique pairs?

Lets say I have an array with several hashes of emails and names. For example I have something like this:

foo = [{id: 1, name: 'Eric Cartman', email: 'eric@southpark.com'},
{id: 2, name: 'Eric Cartman', email: 'cartmanfamily@gmail.com'},
{id: 3, name: "Cartman's mom", email: 'cartmanfamily@gmail.com'},
{id: 4, name: 'Eric Cartman', email: 'eric@southpark.com'}]


How can I use
.uniq
to return unique values based on the combination of name and email? For example I want to return something like this:

[{id: 1, name: 'Eric Cartman', email: 'eric@southpark.com'},
{id: 2, name: 'Eric Cartman', email: 'cartmanfamily@gmail.com'},
{id: 3, name: "Cartman's mom", email: 'cartmanfamily@gmail.com'}]

Answer

foo.uniq should work just fine. Since

{name: "cartman", email: "cartman@sp.com"} == {name: "cartman", email: "cartman@sp.com"} # => True
{name: "stan", email: "stan@sp.com"} == {name: "cartman", email: "cartman@sp.com"} # => False

The == operator check if every field of the hash have the same values. So .uniq will work how you want it to work!

Hope it helped, happy ruby coding!

Edit : if there is more than only the email and name field you should use the uniq method with a block :

foo.uniq { |x| [x[:name], x[:email]] }

It will keep only the uniq combination of the name and email.