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 Landgraf 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]

···

--
Paul Lutus
http://www.arachnoid.com

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.

···

On 10/27/06, Nico Landgraf <nico@nico-landgraf.de> wrote:

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.

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

Here's a one-liner:

aTemp.reject { |x| (aTemp - ).size == aTemp.size - 1 }.uniq

=> [1, 2]

Mike Dvorkin
http://www.rubywizards.com

···

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

thanks paul,

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

Paul Lutus wrote:

···

Nico Landgraf 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]