Please advise if the code is correct or there is a better version and also how to sort the Array in descending orders & the output to be like that:
A program that takes a user’s input, then builds a hash from that input. Each key in the hash will be a word from the user; each value will be the number of times that word occurs. For example, if our program gets the string “the rain in Spain falls mainly on the plain,”
print "What is the sentence that needs to be analysed? "
sentence = gets.chomp
#puts sentence
#Text to Array
my_array = sentence.split
#Create the Hash
word_frequency = Hash.new(0)
#Iterate through the given array in the built Hash
my_array.each { |word|
word_frequency[word] += 1
}
puts word_frequency
Needed Output to be if we run the code:
I love coding to the moon and love web coding
Love 2
coding 2
I 1
to 1
..... etc.