Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicates in a hash in Ruby on Rails?

I have a hash like so:

[
  {
    :lname => "Brown",
    :email => "[email protected]",
    :fname => "James"
  },
  {
    :lname => nil,
    :email => "[email protected]",
    :fname => nil
  },
  {
    :lname => "Smith",
    :email => "[email protected]",
    :fname => "Brad"
  },
  {
    :lname => nil,
    :email => "[email protected]",
    :fname => nil
  },
  {
    :lname => "Smith",
    :email => "[email protected]",
    :fname => "Brad"
  },
  {
    :lname => nil,
    :email => "[email protected]",
    :fname => nil
  }
]

What I would like to learn how to do is how to remove a record if it is duplicate. Meaning, see how there are several "[email protected]" how can I remove the duplicate records, meaning remove all the others that have an email of "[email protected]".... Making email the key not the other fields?

like image 853
AnApprentice Avatar asked Mar 06 '11 02:03

AnApprentice


People also ask

How do I remove a duplicate element from an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

What is hash in Ruby on Rails?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.


1 Answers

In Ruby 1.9.2, Array#uniq will accept a block paramater which it will use when comparing your objects:

arrays.uniq { |h| h[:email] }
like image 137
dnch Avatar answered Oct 05 '22 16:10

dnch