Created
March 24, 2019 16:47
-
-
Save JeffCohen/12764c4e2ba1058bac1ba55492a9c691 to your computer and use it in GitHub Desktop.
Pluck values from a Ruby array of hashes, like ActiveRecord#pluck
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
def pluck(*args) | |
self.map { |item| args.map { |arg| item[arg] || item[arg.to_sym] || item[arg.to_s]}.flatten } | |
end | |
end | |
# Example: | |
# data = [ { "name" => "Cookie Monster", "color" => "blue", "id" => "1" }, | |
# { "name" => "Kermit the Frog", "color" => "green", "id" => "2" } | |
# { "name" => "Big Bird", "color" => "blue", "id" => "3" } | |
# ] | |
# | |
# data.pluck("id", "name}) # => [ ["1", "Cookie Monster"], ["2", "Kermit the Frog"], ["3", "Big Bird"] ] | |
# | |
# It is indifferent to strings or hashes: | |
# | |
# data.pluck(:id", :name}) # => [ ["1", "Cookie Monster"], ["2", "Kermit the Frog"], ["3", "Big Bird"] ] | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment