From: joshua.goodall@... Date: 2019-07-16T07:13:33+00:00 Subject: [ruby-core:93811] [Ruby master Feature#15975] Add Array#pluck Issue #15975 has been updated by inopinatus (Joshua GOODALL). I think that's pretty limited. #pluck is a fairly crude method, fine for Rails but hardly befitting the Ruby standard library. I'd much rather use a higher-order function and get somewhere much more interesting. By instead implementing `Array#to_proc` (which doesn't currently exist) as something that applies to_proc to its own elements in turn, we can get somewhere much more interesting: ```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 ``` we can now do some very nice things just with existing syntax: ```ruby # data people = [{name: "Park", age: 42}, {name: "Lee", age: 31}] keys = people.keys # single item extraction :name.then &people #=> ["Park", "Lee"] people.to_proc[:name] #=> ["Park", "Lee"] # multiple item extraction keys.then &people #=> [["Park", 42], ["Lee", 31]] people.to_proc[:name, :age] #=> [["Park", 42], ["Lee", 31]] # multiple invocation names.map(&[:upcase, :length]) #=> [["PARK", 4], ["LEE", 3]] ``` Could work as `Enumerable#to_proc` instead. ---------------------------------------- Feature #15975: Add Array#pluck https://bugs.ruby-lang.org/issues/15975#change-79679 * 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: