From: connor.james.shea@... Date: 2020-12-06T17:18:39+00:00 Subject: [ruby-core:101265] [Ruby master Feature#15975] Add Array#pluck Issue #15975 has been updated by connorshea (Connor Shea). I was going to suggest the same thing because I think it's a very useful shorthand! Here's an example I run into a lot when manipulating data in my Ruby scripts. ``` ruby # Lets say I have an array of hashes representing video games (this is pretty # common because I write a decent amount of scripts manipulating data in Ruby). games = [ { title: "Half-Life 2", steam_id: 1 }, { title: "Portal", steam_id: 2 }, { title: "Portal 2", steam_id: 3 } ] # If I want to get the Steam IDs for all those, for example to match this # dataset with another dataset to find overlaps, I need to use a `map` like # this: games.map { |game| game[:steam_id] } #=> [1, 2, 3] # That code above doesn't really spark joy, it's pretty lengthy for something # that should be very simple. # What I _want_ to do is something like this, but since these are just hash # keys, I can't: games.map(&:steam_id) #=> undefined method `steam_id' # The best solution would be a `#pluck` method: games.pluck(:steam_id) #=> [1, 2, 3] # This sparks joy! ``` Please consider adding a #pluck method on Enumerable ������������� Ideally it'd accept more than one argument to get multiple values at once, but that's not really a deal-breaker for me if we don't include it. Maybe it could be called #pick, #each_dig, #map_keys, or something else? ---------------------------------------- Feature #15975: Add Array#pluck https://bugs.ruby-lang.org/issues/15975#change-88945 * Author: lewispb (Lewis Buckley) * Status: Open * Priority: Normal ---------------------------------------- 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: