Home > Back-end >  Is this the best way for the below needed Ruby application? [Help in Arrays]
Is this the best way for the below needed Ruby application? [Help in Arrays]

Time:09-15

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.

CodePudding user response:

sentence = "Is this the best way for the below needed Ruby application?"

sentence.split.tally.sort_by { |_word, count| - count }.to_h

# => {"the"=>2, "Is"=>1, "this"=>1, "best"=>1, "way"=>1, "for"=>1, "below"=>1, "needed"=>1, "Ruby"=>1, "application?"=>1}

Firstly tokenize sentence to words array, than tally makes hash where key is word and value is count, than sort descending

You can also sort like this

sentence.split.tally.sort_by(&:last).reverse.to_h

Also you can use unified case, for example with String#upcase method and to avoid capturing punctuation it's possible to use String#scan method

sentence.upcase.scan(/[[:word:]-] /).tally.sort_by(&:last).reverse.to_h

CodePudding user response:

After many trails & @mechnicov I had reached the below and hope to hear reviews:

print 'What is the sentence that needs to be analysed? '
sentence = gets.chomp

# Convert Text to Array:
my_array = sentence.split

# Create the Hash called histogram
histogram = Hash.new(0) # zero added as a counter for iterate through word and add on it if exist

my_array.each do |word|
  histogram[word]  = 1
end

# Sort descending by values
sorted_histogram = histogram.sort_by { |_k, v| v }.reverse

#Print final output: 
sorted_histogram.each do |_word, _count|
  puts _word   ' '   _count.to_s
end


  • Related