Last active
July 13, 2016 02:35
-
-
Save barnett/0ab889fe64a47e73b054 to your computer and use it in GitHub Desktop.
Ruby Array#count magic
This file contains hidden or 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
# Data | |
# We need to get a count for # of votes for different candidates | |
>> VOTES = { | |
?> "Napoleon" => "Pedro", | |
?> "Don" => "Summer", | |
?> "Deb" => "Pedro", | |
?> "Randy" => "Summer", | |
?> "Trisha" => "Pedro", | |
?> } | |
=> {"Napoleon"=>"Pedro", "Don"=>"Summer", "Deb"=>"Pedro", "Randy"=>"Summer", "Trisha"=>"Pedro"} | |
# Good | |
>> VOTES.values.select{|v| v == "Pedro"}.size | |
=> 3 | |
# Better | |
>> VOTES.values.count{|v| v == "Pedro"} | |
=> 3 | |
# Best | |
>> VOTES.values.count("Pedro") | |
=> 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment