Array::uniq { block } ?

M

Martin DeMello

Robert Klemme said:
module Enumerable
def uniq_by
h = {}; inject([]) {|a,x| h[yield(x)] ||= a << x}
end
end
=> [2, 7, 9]

Beautiful about this version is that it does not need the "; h" at the end
of the inject block and no ".values", too... :)

Very nice indeed.

martin
 
F

Florian Gross

Robert said:
Also (as optimization) you could use "state << item" instead of "state +
[item]" because Array#<< returns self. This saves you a lot temporary
1element arrays and avoids creating new arrays all the time (Array#+
creates a new Array). :)

I dislike having the block of .inject having side effects. That sort of
defeats the purpose IMHO.
 
D

David A. Black

Hi --

Robert said:
Also (as optimization) you could use "state << item" instead of "state +
[item]" because Array#<< returns self. This saves you a lot temporary
1element arrays and avoids creating new arrays all the time (Array#+
creates a new Array). :)

I dislike having the block of .inject having side effects. That sort of
defeats the purpose IMHO.

I don't think it's a side effect, since it's just injecting something
into the accumulator or "injectee". This might be exactly what you
want if, for example, you have multiple references to the accumulator:

x = []
y = x

["a","b","c"].inject(x) {|m,n| m << n.upcase}

puts y # ["A", "B", "C"]

Otherwise in a case like this you could just use #map.


David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top