Skip to content

Instantly share code, notes, and snippets.

@micho
Last active December 17, 2015 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micho/5669194 to your computer and use it in GitHub Desktop.
Save micho/5669194 to your computer and use it in GitHub Desktop.
Count occurrences
class Array
# Takes %(apple apple strawberry orange orange apple) and returns { apple: 3, orange: 2, strawberry: 1 }
def occurrences
r = {}
group_by {|i| i}.each{|k,v| r[k] = v.count}
sorted = {}
r.sort_by {|k,v| -v}.each {|i| sorted[i[0]] = i[1] }
sorted
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment