This project is archived and is in readonly mode.
Adding Array.uniq_by(proc) to core_ext, allowing selection of unique elements based on their response to a proc
-
Joey Schoblaska
I can't download the original attachment, so trying another upload to see if that fixes it.
-
Yehuda Katz (wycats)
- State changed from new to open
- Assigned user set to Yehuda Katz (wycats)
- Milestone cleared.
Looks good to me. Are there any parts of the Rails internals that you could see benefiting from this patch?
-
Joey Schoblaska
Thanks! I can't think of any off the top of my head, but I'll definitely take a look.
-
Elliot Winkler
+1 for the idea. I wrote a version of the method a while back (except using inject + a hash instead of a select within a select as you've got). It does come in handy.
Question: Why does your uniq_by accept a Proc object? Shouldn't it just accept a block? I.e.:
arr.uniq_by {|x| ... }as opposed to
arr.uniq_by(Proc.new {|x| ... }) -
Joey Schoblaska
Thanks for the suggestion. You're right - blocks result in much nicer-looking method calls than procs. I updated the patch to use blocks instead.
-
Pratik
Why not just override Array#uniq and uniq! instead of adding a new method ?
-
Joey Schoblaska
It seemed like overriding a Ruby method as common as [].uniq might cause confusion so I opted to create a new, explicitly-named method instead.
-
Pratik
I think doing something like this might be ok :
def uniq if block_give? select {|item| select {|i| yield(i) == yield(item)}.index(item) == 0 } else super end endJust a thought. I'm fine with a new method too. I just think it's more intuitive to make uniq accept a block.
-
Dan Barry
Joey's implementation O(n^3 / m) where n is the number of elements in the array and m is the number of unique values. I came up with a different implementation that is more performant: http://gist.github.com/159799
-
Cheah Chu Yeow
I like Pratik's idea of overriding uniq. There've been more than a few times that I've used uniq expecting that it takes a block.
Otherwise I like the general idea of this patch :)
-
Evgeniy Dolzhenko
+1 since was always using the same method for a long time available in Facets http://facets.rubyforge.org/git?p=facets.git;a=blob_plain;f=lib/cor...
Also if you guys came with more efficient implementation I think it's worth sending it to Facets as well.
-
Evgeniy Dolzhenko
Ok, the Facets link got crippled, here is the shortened one http://bit.ly/QMjcp
-
jack dempsey (jackdempsey)
+1 I could use something like this right now. Dan's patch is nice as well--those speed improvements are excellent.
-
Dan Peterson
Just discovered this ticket while Googling for my version of Enumerable#uniq_by. ;)
Here's the version I came up with if it helps: http://gist.github.com/168544
-
José Valim
- State changed from open to resolved
- Assigned user changed from Yehuda Katz (wycats) to José Valim
That was already added on master.
