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?
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.
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.
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] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With