Array#uniq doesn't take block... Why?

Hi all.

Why Array#uniq doesn't take block? I think it's nice if we can pass block. I know it's enough when object is simple like Fixnum.

[1,2,2,3].uniq #=> [1,2,3]

but when it comes to complex object like ActiveRecord model

Company.all.uniq { |c| c.name }

I found a patch (Tickets - Ruby on Rails - rails 1595-patch-for-activesupport-that-arrayuniq-and-uniq-supports-blocks) that enables this feature but it was rejected unfortunately. Anyone have an idea why it's rejected?

Thanks.

How would it know which record to keep and which to reject when it found two entries with the same name?

Colin

Or perhaps I misunderstand, perhaps you just mean Company.all.map(&:name).uniq

Colin

>> Hi all. >> >> Why Array#uniq doesn't take block? I think it's nice if we can pass >> block. >> I know it's enough when object is simple like Fixnum. >> >> [1,2,2,3].uniq #=> [1,2,3] >> >> but when it comes to complex object like ActiveRecord model >> >> Company.all.uniq { |c| c.name } > > How would it know which record to keep and which to reject when it > found two entries with the same name?

Or perhaps I misunderstand, perhaps you just mean Company.all.map(&:name).uniq

Sounds like he wants uniq_by: http://redcorundum.blogspot.com/2007/02/have-you-seen-that-key.html

Colin

--Greg

Apart from the merits of the idiom itself, generally speaking Active Support extends Ruby mostly to ease the development of Rails itself, and only adds other core extensions when they are clearly of benefit for almost any web application. That's the rule of thumb, it doesn't mean you won't find a counterxample, but it's what guides additions.

In that sense Active Support has a different goal than Facets, for example.

Collin

Company.all.map(&:name).uniq returns an array of strings but what I want here is an array of company objects. So that's not what I want here.

Xavier

I under the idea of core extensions.

Gregory

That's exactly what I wanted. FYI, I didn't realize but Array#uniq_by in core_ext does the trick.

Thank you all for your quick reply!

Shou

Or uniq on 1.9.2 :wink: