dimanche 29 mars 2015

Count Number of Words on Each Sentence in Ruby

How do you count the words on each sentence if you have a bunch of sentences (a paragraph or two).



string = "hello world. Hello world."

#I first split sentences into an element like so, first maybe initialized variables to count sentence, then words within the sentence
sentencecount = 0
wordcount = 0

string.split(".").each do |sentence|
sentencecount += 1 #track number of sentence
sentence.(/\W+/).each do |word|
wordcount += 1 #to track number of word
end

puts "Sentence #{sentencecount} has #{wordcount} words."

end


Output:



Sentence 1 has 2 words
Sentence 2 has 5 words


Second line should say 2 words not 5. Any ideas? Yes two loops. Maybe there are better ways to do this but this is how I understand the program.


Aucun commentaire:

Enregistrer un commentaire