How to get only the duplicatet items from an array

hi all,

is there a oneline to get only the duplicatet item from an array?

i have an array like this
aTemp = [1, 1, 2, 2, 3, 4]
and i want to know, which items are duplicatet.

i thought i can do it like
aTemp - aTemp.uniq

[1, 1, 2, 2, 3, 4] - [1, 2, 3, 4] => [1, 2]
like inside the manual

but i get only an empty array

so i found an bad solution and hope you can help me to get the right
way.

thanks for your help
nico

Nico L. wrote:

i have an array like this
aTemp = [1, 1, 2, 2, 3, 4]
and i want to know, which items are duplicatet.

/ …

so i found an bad solution and hope you can help me to get the right way.

#!/usr/bin/ruby -w

a = [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9]

dups = []

hash = {}

a.each do |item|
dups << item if hash[item]
hash[item] = true
end

p dups

[1, 1, 1, 1, 2, 2, 2, 9, 9]

On 10/27/06, Nico L. [email protected] wrote:

[1, 1, 2, 2, 3, 4] - [1, 2, 3, 4] => [1, 2]
like inside the manual

but i get only an empty array

so i found an bad solution and hope you can help me to get the right way.

Here’s one way:
irb(main):001:0> h = Hash.new(0)
=> {}
irb(main):002:0> array = [1,1,2,2,3,4,1]
=> [1, 1, 2, 2, 3, 4, 1]
irb(main):003:0> duplicates = array.select {|e| h[e] += 1; h[e] == 1}
=> [1, 2, 3, 4]
irb(main):004:0>

There are shorter ways, but I find that one to be pretty readable. The
resulting array doesn’t contain duplicates, just one each of the
entries that appeared multiple times in the input array.

It also makes it easy to find out how many times something appeared,
if you need that.

h[1] will return 3, for example.

thanks paul,

looks like my way.
i hoped there is a smarter way in ruby.

On Oct 27, 2006, at 10:35 AM, Nico L. wrote:

aTemp = [1, 1, 2, 2, 3, 4]

Here’s a one-liner:

irb> aTemp.reject { |x| (aTemp - [x]).size == aTemp.size - 1 }.uniq
=> [1, 2]

Mike D.
http://www.rubywizards.com

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs