Skip to content

Instantly share code, notes, and snippets.

@ccurtisj
Last active December 14, 2015 09:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccurtisj/5066333 to your computer and use it in GitHub Desktop.
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.
#
# 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