How do I count the frequencies of the letters in user input?

我只是一个虾纸丫 提交于 2019-12-02 22:18:51

问题


How do I count the frequency of letters that appear in the word "supercaliforniamightly" when the user enters a word like that in Ruby, and print out stars or asterisks to count the number of letters that appear?

Here's my code:

puts "Enter string: "
text= gets.chomp
text.downcase! 
words = text.split(//)

frequencies = Hash.new(0)

words.each{|item| frequencies[item] +=1}

frequencies = frequencies.sort_by{ |item, amount| amount}
frequencies.reverse! 

frequencies.each do |item, amount|
    puts item + " " + amount.to_s 
   end

The output I want is something like:

Enter a string: 
uuuuiiii
u , 4 ****
i , 4 ****

回答1:


I changed the output a little bit (removed the space before the comma) so that I don't look like uneducated.

puts "Enter string: "
gets.chomp.downcase
.each_char.with_object(Hash.new(0)){|c, h| h[c] += 1}
.sort_by{|_, v| v}
.reverse
.each{|k, v| puts k + ", " + v.to_s + " " + "*" * v}

Output:

Enter string: 
uuuuiiii
i, 4 ****
u, 4 ****


来源:https://stackoverflow.com/questions/26457536/how-do-i-count-the-frequencies-of-the-letters-in-user-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!