[ruby-core:93812] [Ruby master Feature#15975] Add Array#pluck
From:
manga.osyo@...
Date:
2019-07-16 07:47:05 UTC
List:
ruby-core #93812
Issue #15975 has been updated by osyo (manga osyo).
> we can now do some very nice things just with existing syntax:
The sample code is invalid.
Is this?
```ruby
class Array
def to_proc
Proc.new do |head, *tail|
collect(&:to_proc).collect do |ep|
ep_head = ep[head]
tail.empty? ? ep_head : [ep_head] + tail.collect(&ep)
end
end
end
end
# data
people = [{name: "Park", age: 42}, {name: "Lee", age: 31}]
keys = people.first.keys
# single item extraction
p :name.then &people #=> ["Park", "Lee"]
p people.to_proc[:name] #=> ["Park", "Lee"]
# multiple item extraction
p keys.then &people #=> [["Park", 42], ["Lee", 31]]
p people.to_proc[:name, :age] #=> [["Park", 42], ["Lee", 31]]
# multiple invocation
names = people.map { @1[:name] }
p names.map(&[:upcase, :length]) #=> [["PARK", 4], ["LEE", 3]]
```
https://wandbox.org/permlink/4oVOzULhwKsu4gB5
----------------------------------------
Feature #15975: Add Array#pluck
https://bugs.ruby-lang.org/issues/15975#change-79680
* Author: lewispb (Lewis Buckley)
* Status: Open
* Priority: Normal
* Assignee:
* Target version:
----------------------------------------
Inspired by https://github.com/rails/rails/issues/20339
While developing web applications I've often wanted to quickly extract an array of values from an array of hashes.
With an array of objects, this is possible:
```rb
irb(main):001:0> require 'ostruct'
=> true
irb(main):002:0> [OpenStruct.new(name: "Lewis")].map(&:name)
=> ["Lewis"]
```
This PR adds Array#pluck allowing this:
```rb
irb(main):001:0> [ {name: "Lewis"} ].pluck(:name)
=> ["Lewis"]
```
without this PR:
```rb
irb(main):001:0> [ {name: "Lewis"} ].map { |item| item[:name] }
=> ["Lewis"]
```
Implemented here:
https://github.com/ruby/ruby/pull/2263
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>