Removing array duplicates where a subset is unique

On Jul 19, 2009, at 3:43 PM, 7stud – wrote:

Chuck R. wrote:

(And Joel, I have presorted the array prior
to removing the dupes so I have already taken care of the ordering

That’s well and good, but in the process of using a hash to remove the
duplicates, the result will be out of order. See example below.

True, but in my case the order only matters for picking the first of
the duplicates. I understand hashes in 1.8 don’t maintain order, but
that isn’t relevant since I don’t care about output order.

I suppose I could have written a longer explanation of what I needed,
but I favored brevity over those other details.


On Jul 19, 2009, at 5:07 PM, Siep K. wrote:


Facets has enumerable#uniq_by implemented like this:

def uniq_by #:yield:
h = {}; inject([]) {|a,x| h[yield(x)] ||= a << x}

Ooh, I like this one too. I’ll try it out and see what kind of
performance I get. I understand that #inject performance is weak in
MRI 1.8, but I primarily use JRuby where it doesn’t share the same
performance issues as the C version.


7stud – wrote:

No, but whenever I see ||= now, I get scared. :frowning:

I do to! It looks like a very angry gnome.

David A. Black wrote:

I’m still waiting to see a use-case for &&=. I’ve come close to
thinking I had one once or twice, but it always turns out I didn’t.

Not terribly useful, but…

line = sock.gets
line &&= line.chomp
log.debug “line is #{line.inspect}”

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