[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: uniq on custom objects

Peña, Botp

10/29/2007 9:30:00 AM

From: daniel åkerud [mailto:daniel.akerud@gmail.com]
# a = [Obj.new("apa", 1), Obj.new("apa", 2), Obj.new("smisk", 3)]
# => [#<Obj:0x31baca8 @number=1, @name="apa">, #<Obj:0x31bac80
# @number=2, @name="apa">, #<Obj:0x31bac58 @number=3, @name="smisk">]
#
# a.uniq
# => [#<Obj:0x31baca8 @number=1, @name="apa">, #<Obj:0x31bac80
# @number=2, @name="apa">, #<Obj:0x31bac58 @number=3, @name="smisk">]
#
# But i want only one instance of "apa", and it doesn't matter
# which. Is there something else I have to override?

hmm, that's a unique requirement for uniq :)
btw, there was a recent thread on removing dups, wc is similar in a way to uniq.

anyway, try

~> a.group_by(& :name).map{|_,v|v[0]}

=> [#<Obj:0xba8c90 @name="smisk", @number=3>, #<Obj:0xba8d08 @name="apa", @number=1>]

sorry, i'm in ruby1.9 box right now. but the idea is that i group the objects by name, and just get the first on each group.

kind regards -botp