I just thought I would put in my 2 cents. I actually had to create a
script that would run through a file and find all the duplicate account
numbers and the number of times they were duplicated and write that to a
new file.
Jeremy W. wrote:
I actually had to … find all the duplicate account
numbers and the number of times they were duplicated and … .
…
~Jeremy
A much less verbose ‘nil’ fix of the original version would be to use
[v] instead of v:
a = [nil,1,2,2,3,nil]
p a.uniq.map {|v| (a - [v]).size < (a.size - 1) ? [v] :
nil}.compact.flatten
=> [nil, 2]
This fix does not work for a = [nil,1,2,[7],2,[7],3,nil], but the
previous version using “(a.size - a.nitems > 1) ? …” does. Ruby 1.9
though is said to introduce a non-greedy Array#flatten:
Ruby 1.9
a = [nil,1,[7],2,2,[7],3,nil]
p a.uniq.map {|v| (a - [v]).size < (a.size - 1) ? [v] :
nil}.compact.flatten(1)
=> [nil, [7], 2]
a = [1,2,3,2,1]
b = a & a
b = [1,2,3]
---------------------------------------------------------------|
~Ari
“I don’t suffer from insanity. I enjoy every minute of it” --1337est
man alive
…but that’s not what the OP wanted. What you’ve written is the same
as the #uniq method.
Don’t feel bad, this thread has been filled with people answering the
wrong question. The original question was roughly “How do I find
out all the elements in the array that are duplicates?”
Solutions to that question would not include ‘3’ in the above results.
It’s unclear to me if %w| a b b b | should include ‘b’ once or twice
in the output, though, and the original poster has not clarified that,
that I can see.
irb(main):057:0> b.uniq.select{|e| (b.reject!{|f| f == e}).size > 1}
Don’t feel bad, this thread has been filled with people answering the
wrong question. The original question was roughly “How do I find
out all the elements in the array that are duplicates?”
Solutions to that question would not include ‘3’ in the above results.
It’s unclear to me if %w| a b b b | should include ‘b’ once or twice
in the output, though, and the original poster has not clarified that,
that I can see.
I think once, since it’s just the quality of being non-unique in
the array that qualifies an object for inclusion. At least, that’s my
understanding, though as one of the people who reimplemented
Array#uniq, I may not be the right person to listen to