Skip to content

Instantly share code, notes, and snippets.

@robvolk
Last active February 15, 2016 19:12
Show Gist options
  • Save robvolk/180307ac7f6c71aaa6a3 to your computer and use it in GitHub Desktop.
Save robvolk/180307ac7f6c71aaa6a3 to your computer and use it in GitHub Desktop.
Count & sort values of a Ruby Array
food = ["bacon", "eggs", "cheese", "eggs", "bacon", "bacon", "bacon"]
food.inject(Hash.new(0)) {|h, k| h[k] += 1; h }.sort_by {|k,v| -1 * v}
# => [["bacon", 4], ["eggs", 2], ["cheese", 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment