[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: how to get only the duplicatet items from an array

Gavin Kistner

10/27/2006 5:55:00 PM

From: Nico Landgraf [mailto:nico@nico-landgraf.de]
> 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.

There are faster ways to do this, but since you asked for a one-line:
a = [1, 1, 2, 2, 3, 4]
duplicates = a.delete_if{ |x| a.grep(x).length == 1 }.uniq
#=> [1, 2]

3 Answers

Nico Landgraf

10/27/2006 5:57:00 PM

0

thanks, yes sir,
thats really what i'm looking for.
could you please post your fast way.

nico

Gavin Kistner wrote:
> From: Nico Landgraf [mailto:nico@nico-landgraf.de]
>> 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.
>
> There are faster ways to do this, but since you asked for a one-line:
> a = [1, 1, 2, 2, 3, 4]
> duplicates = a.delete_if{ |x| a.grep(x).length == 1 }.uniq
> #=> [1, 2]
>

Brad Tilley

10/27/2006 7:12:00 PM

0

Nico Landgraf wrote:
> thanks, yes sir,
> thats really what i'm looking for.
> could you please post your fast way.

Use Set:

irb(main):006:0> a = [1,1,2,2,3,3,4,4]
=> [1, 1, 2, 2, 3, 3, 4, 4]
irb(main):007:0> Set.new(a)
=> #<Set: {1, 2, 3, 4}>

I don't know if it's faster, but it look better IMO.


--
Posted via http://www.ruby-....

William Fisk

10/28/2006 6:55:00 PM

0

another possibility:

>> a=['a','b',7,77,'a','ba',3,7]
=> ["a", "b", 7, 77, "a", "ba", 3, 7]
>> a.inject(Hash.new(0)){|h,v|h[v]+=1;h}.reject{|k,v| v<2}.keys
=> ["a", 7]

--
Posted via http://www.ruby-....