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

后端 未结 1 1511
庸人自扰
庸人自扰 2021-01-27 09:21

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 cou

相关标签:
1条回答
  • 2021-01-27 09:42

    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 ****
    
    0 讨论(0)
提交回复
热议问题