Skip to content

Instantly share code, notes, and snippets.

@JeffCohen
Created March 24, 2019 16:47
Show Gist options
  • Save JeffCohen/12764c4e2ba1058bac1ba55492a9c691 to your computer and use it in GitHub Desktop.
Save JeffCohen/12764c4e2ba1058bac1ba55492a9c691 to your computer and use it in GitHub Desktop.
Pluck values from a Ruby array of hashes, like ActiveRecord#pluck
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