Add Enumerable#pick#38760
Conversation
29ab6f7 to
9beff86
Compare
simi
left a comment
There was a problem hiding this comment.
Looks ok to me since it follows same pattern as pluck and there's probably no chance to get this to Ruby itself, since it is not useful for Enumerable in general.
👍
There was a problem hiding this comment.
Should we normalize to return an empty array like pluck does? Could potentially tap compact! at the end of the map.
There was a problem hiding this comment.
I don't think we can use compact, since we need to keep any nil values that were picked when the enumerable isn't empty. We could add a special case for when it is empty, though.
Using the rubric that pick(...) should be equivalent to pluck(...).first, picking an empty enumerable seems like it should return nil:
irb(main):001:0> [].pluck(:dollar, :cents).first
=> nilThis is how Relation#pick already behaves:
I have a slight preference for aligning with that existing behaviour, although in practice I think the result of calling pick with multiple arguments is usually destructured, so it doesn't matter too much which behaviour we pick choose:
irb(main):001:0> a, b = nil; [a, b]
=> [nil, nil]
irb(main):002:0> a, b = []; [a, b]
=> [nil, nil]
irb(main):003:0> a, b = [nil, nil]; [a, b]
=> [nil, nil]There was a problem hiding this comment.
My objection was more to seeing [] for the pluck return versus [ nil, nil ] for pick, size would be different or similar.
I have a slight preference for aligning with that existing behaviour,
Same, but the nil is the default return for a method call, so it would do that regardless. I like the none? fix.
9ea8fd4 to
72dfcce
Compare
This allows `pick` to be called on an object that could either be an enumerable or a relation. Also clarify the documentation for `Enumerable#pluck`, and add an example of plucking multiple keys to the core extensions guide.
When called on a loaded relation, `pick` will now use the existing results instead of making another query, just like `pluck` does.
72dfcce to
4ffd53f
Compare
|
These ain't slim |
As with
pluck(#20339), it's useful to be able to callpickon loaded relations, unloaded relations, and plain enumerables interchangeably.This also ensures that it's always safe to rewrite
pluck(:title).firstaspick(:title).