Last active
December 17, 2015 20:39
-
-
Save micho/5669194 to your computer and use it in GitHub Desktop.
Count occurrences
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 | |
# 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