Last active
December 26, 2015 18:58
-
-
Save bswinnerton/7197684 to your computer and use it in GitHub Desktop.
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
# Getting a list of unique values and their counts in Ruby | |
languages = ["Ruby", "PHP", "Ruby", "Ruby", "Shell", "PHP", "Ruby", nil, "VimL", "Ruby", "Ruby", "PowerShell", "JavaScript", nil, nil, "PowerShell", "CSS", nil, nil, "Ruby", "PowerShell", "Ruby", "VimL"] | |
########## The ugly way ########## | |
hash = Hash.new(0) | |
languages.each do |language| | |
hash[language] += 1 | |
end | |
counts = hash | |
########## end The ugly way ########## | |
########## The cool, hip, ruby way ########## | |
# Iterate over each member of the languages array, and increment the value of the key in the hash | |
# - Pass a new hash into the iteration, and setting a default value of 0, more info here: http://www.ruby-doc.org/core-2.0.0/Hash.html#method-c-new | |
# - Pass two variables to the block, `hash` and `language` where `hash` == `Hash.new(0)`, and `language` == the current iteration of the array | |
# - Increment the value of the hash where it's key is equal to `language`. For example, hash["Ruby"] is incremented by one when it's in that iteration | |
# - Return the hash when done | |
counts = languages.inject(Hash.new(0)) {|hash,language| hash[language] += 1; hash} | |
########## end The cool, hip, ruby way ########## | |
puts counts | |
# => {"Ruby"=>8, "PHP"=>2, "Shell"=>1, nil=>5, "VimL"=>2, "PowerShell"=>3, "JavaScript"=>1, "CSS"=>1} | |
# And if you want it sorted: (more info on how this works, here: http://www.ruby-doc.org/core-2.0.0/Hash.html#method-c-5B-5D) | |
puts ordered_counts = Hash[counts.sort_by {|k,v| v}.reverse] | |
# => {"Ruby"=>8, nil=>5, "PowerShell"=>3, "VimL"=>2, "PHP"=>2, "Shell"=>1, "JavaScript"=>1, "CSS"=>1} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment