Last active
December 14, 2015 09:38
-
-
Save ccurtisj/5066333 to your computer and use it in GitHub Desktop.
Quick helper to get all unique values present for objects in a given array. Useful for debugging.
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
# | |
# Returns a hash of all unique values for a given field and the number of objects | |
# in the array which have that value. | |
# ex: | |
# Post.all.uniq_value_counts(:status) | |
# => { | |
# "published" => 10, | |
# "draft" => 13, | |
# "archived" => 34 | |
# } | |
# | |
class Array | |
def uniq_value_counts(field) | |
self.inject(Hash.new(0)) do |hash, obj| | |
hash[obj.send(field)] += 1 | |
hash | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment