我有这个问题计算带有哈希的字母:
#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.
这是我的解决方案:
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")
为了让我按降序对其进行排序,我不得不输入这段代码:
Hash[count.sort_by {|k,v| v}.reverse]
我还能做哪些折射?还有其他方法可以进行降序排序吗?
有没有更好的方法来做到这一点?