This project is archived and is in readonly mode.

#2957 ✓resolved
Joey Schoblaska

Adding Array.uniq_by(proc) to core_ext, allowing selection of unique elements based on their response to a proc

Reported by Joey Schoblaska | July 25th, 2009 @ 11:46 PM | in 3.0.2

Oftentimes it's necessary to select some unique elements from an array based on various attributes. For instance, if you have an array of posts and you want to select only posts that have a unique author_id; or posts with a unique combination of author_id and created_at date to get an array with one post per user per day. It's usually possible to do this with SQL when you're dealing with AR objects, but that's not always an option, so I wrote this patch to address those cases.

    array = [{:id => 1, :val => 1}, 
             {:id => 2, :val => 1},
             {:id => 3, :val => 2},
             {:id => 4, :val => 3}]
             
    array.uniq_by(Proc.new {|a| a[:val]}).map{|a| a[:id]} == [1,3,4]

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Attachments

Tags

Pages