I have this problem counting letters with a hash:
#Counting with hashes!
#Experiment by writing a couple of short programs that will use Hashes to count
#objects by incrementing a key value.
#Write a funcition that will count the number of letters in a phrase.
#Example "cat in the hat" -> return: {"t"=>3, "h"=>2, "a"=>2, "i"=>1, "n"=>1, "e"=>1, "c"=>1}
#From descending order. Largest to smallest. Do not include spaces.
Here is my solution:
def count_letters(str)
count = Hash.new(0)
str.delete(" ").each_char { |letter| count[letter]+=1}
Hash[count.sort_by {|k,v| v}.reverse]
end
print count_letters("cat in the hat")
In order for me to sort it in descending order, I had to put this snippet of code:
Hash[count.sort_by {|k,v| v}.reverse]
What more refractoring can I do? Is there another way to do descending sort?
Is there better a way of doing this?