8. Create a Histogram -- Weird integer popping up on my block of code


#1


  1. Create a Histogram

My code works fine. It splits up all the words, orders them (haven't figured out how to alphabetize them yet, but no matter). The only thing is when you run it it gives you a random number at the beginning -- I think it's a count of punctuation marks, but I'm not sure. Any ideas?


puts "Text please: "
text = gets.chomp.downcase

regex = /[?!()., ]/
words = text.split(regex)
frequencies = Hash.new(0)
words.each { |word| frequencies[word] += 1 }
frequencies = frequencies.sort_by {|a, b| b }
frequencies.reverse!
frequencies.each { |word, frequency| puts word + " " + frequency.to_s }
nil


#2

Test run...

Text please: 
 You're running Ruby version 1.8.7. To get started, type 
 in the console below or the text editor to the left. Want 
 to learn more about Ruby?

3
the 3
to 3
ruby 2
started 1
version 1
1 1
type 1
below 1
about 1
want 1
you're 1
in 1
text 1
editor 1
learn 1
console 1
or 1
running 1
8 1
7 1
more 1
get 1
left 1

Examine the raw data:

=> [["", 3], ["the", 3], ["to", 3], ["ruby", 2], ["started", 1], ["version", 1], ["1", 1], ["type", 1], ["below", 1], ["about", 1], ["want", 1], ["you're", 1], ["in", 1], ["text", 1], ["editor", 1], ["learn", 1], ["console", 1], ["or", 1], ["running", 1], ["8", 1], ["7", 1], ["more", 1], ["get", 1], ["left", 1]]

Somehow the empty string is being counted. That is where the 3 comes from, but I'm at a loss to explain how the empty string got in there.

frequencies = frequencies.sort_by {|a, b| b }

To sort alphabetically, use a in the block.

frequencies = frequencies.sort_by {|a, b| a }

#3

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