Shuaib Zahda wrote:
> Hello
>
> I am trying to output the duplicate elements in an array. I looked into
> the api of ruby I found uniq method which outputs the array with no
> duplication. What i want is to know which elements is duplicated.
> For example
>
> array = ["apple", "banana", "apple", "orange"]
> => ["apple", "banana", "apple", "orange"]
> array.uniq
> => ["apple", "banana", "orange"]
>
> I want the method to tell me that apple is the duplicated element
>
> I tried this but it does not work
>
> array - array.uniq
>
> any idea
>
> Regards
> Shuaib
>   

I don't know a good way to do it, but one way to get the result would be 
to force it into a hash since that eliminates duplicates.


I'm sure there's a better way to do it, but here's what I got.

array = ["apple", "banana", "apple", "orange", "fat", "cow", "cow"]
h = Hash.new
duplicates = []

array.each {|item|
    if h.has_key?(item) then
        duplicates << item
    else
        h[item] = 0 #it doesn't matter what we store
    end
}

puts duplicates

Cheers
Mohit.