Skip to content

Instantly share code, notes, and snippets.

@sj26
Created December 9, 2011 03:05
Show Gist options
  • Save sj26/1449962 to your computer and use it in GitHub Desktop.
Save sj26/1449962 to your computer and use it in GitHub Desktop.
Gather values from an array of hashes
class Array
def pluck key
map { |hash| hash[key] }
end
end
[{:number => "1"}, {:number => "2"}, {:number => "3"}].pluck(:number)
# => ["1", "2", "3"]
@Ruxton
Copy link

Ruxton commented Dec 9, 2011

[{:number => "1"}, {:number => "2"}, {:number => "3"}].map(&:first).map(&:last)
# => ["1", "2", "3"]

@sj26
Copy link
Author

sj26 commented Dec 9, 2011

Okay, but (slightly more realistically):

[{:odd => "1", :even => "2"}, {:odd => "3", :even => "4"}, {:odd => "5", :even => "6"}].pluck(:even)
# => ["2", "4", "6"]

Whereas:

[{:odd => "1", :even => "2"}, {:odd => "3", :even => "4"}, {:odd => "5", :even => "6"}].map(&:first).map(&:last)
# => ["1", "3", "5"]

Also, we need to be key-order agnostic, so map(&:second) isn't viable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment