Advertisement
karlakmkj

2nd mini program using Hash

Sep 2nd, 2021
501
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.78 KB | None | 0 0
  1. # 2nd created mini program using Hash
  2.  
  3. puts "What is your favourite food? "
  4. text = gets.chomp  # get user input in string of many words
  5. words = text.split  # split the string text into separate words
  6.  
  7. frequencies = Hash.new(0)  # create a new Hash (dictionary) with default value 0
  8.  
  9. words.each do |w|  # for each of the word
  10.   frequencies[w] +=1  # if is the same word, add value 1 to the key; else is value 1 to the word itself
  11. end
  12. puts frequencies
  13.  
  14. frequencies = frequencies.sort_by do |w, count| count  # sort the Hash according to the count value
  15. end
  16. frequencies.reverse!  # and reverse to see the highest count on top  
  17.  
  18. frequencies.each do |name, count|  
  19.   puts name + " " + count.to_s  # to convert number into string type and print them together in this format
  20. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement