Https://discuss.codecademy.com/c/ruby/create-a-histogram/


#1

i cant understand this :
please can someone explain this line by line

puts "Enter some text here:"
text = gets.chomp

words = text.split(" ")
frequencies = Hash.new(0)

words.each do |word|
frequencies[word] += 1
end
frequencies = frequencies.sort_by do |word, count|
count
end
frequencies.reverse!
frequencies.each do |word , freq|
puts word + " " + freq.to_s
end


#2

We’ve already covered the above in an earlier topic so will move on to the remaining lines.

The above takes a hash which we no longer have need of and repurposes the variable to accept the array of tuples that the sort_by method returns.

Since the array is sorted in ascending order, and we want the highest frequencies near the top, we reverse the array order, in place.

This is the output phase where we iterate over the tuples and print the word, frequency pair in each one. The frequency in the data is a number, therefore it is converted to a string so it can be concatenated.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.