Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 2nd created mini program using Hash
- puts "What is your favourite food? "
- text = gets.chomp # get user input in string of many words
- words = text.split # split the string text into separate words
- frequencies = Hash.new(0) # create a new Hash (dictionary) with default value 0
- words.each do |w| # for each of the word
- frequencies[w] +=1 # if is the same word, add value 1 to the key; else is value 1 to the word itself
- end
- puts frequencies
- frequencies = frequencies.sort_by do |w, count| count # sort the Hash according to the count value
- end
- frequencies.reverse! # and reverse to see the highest count on top
- frequencies.each do |name, count|
- puts name + " " + count.to_s # to convert number into string type and print them together in this format
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement