Created
December 9, 2011 03:05
-
-
Save sj26/1449962 to your computer and use it in GitHub Desktop.
Gather values from an array of hashes
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 key | |
map { |hash| hash[key] } | |
end | |
end | |
[{:number => "1"}, {:number => "2"}, {:number => "3"}].pluck(:number) | |
# => ["1", "2", "3"] |
Ruxton
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