简体   繁体   中英

Counting and computing the average length of words in ruby

I'm trying to debug a program in ruby that is meant to compute and print the average length of words in an array.

words = ['Four', 'score', 'and', 'seven', 'years', 'ago', 'our', 'fathers', 'brought', 'forth', 'on', 'this', 'continent', 'a', 'new', 'nation', 'conceived', 'in', 'Liberty', 'and', 'dedicated', 'to', 'the', 'proposition', 'that', 'all', 'men', 'are', 'created', 'equal']

word_lengths = Array.new

words.each do |word|

  word_lengths << word_to.s

end

sum = 0
word_lengths.each do |word_length|
  sum += word_length
end
average = sum.to_s/length.size
puts "The average is " + average.to_s

Obviously, the code is not working. When I run the program, I receive an error message that says the string '+' can't be coerced into fixnum (typeerror).

What do I do no make the code compute the average length of the strings in the array?

Try :

words.join.length.to_f / words.length

Explanation:

This takes advantage of chaining methods together. First, words.join gives a string of all the characters from the array:

'Fourscoreandsevenyearsagoourfathersbroughtforthonthiscontinentanewnationconcei
vedinLibertyanddedicatedtothepropositionthatallmenarecreatedequal'

We then we apply length.to_f giving the length as a float (using a float ensures an accurate final result):

143.0

We then divide the above using / words.length :

4.766666666666667

Try this.

words = ['Four', 'score', 'and', 'seven', 'years', 'ago', 'our', 'fathers',
 'brought', 'forth', 'on', 'this', 'continent', 'a', 'new', 'nation',
 'conceived', 'in', 'Liberty', 'and', 'dedicated', 'to', 'the', 'proposition',
 'that', 'all', 'men', 'are', 'created', 'equal']


sum = 0
words.each do |word|
  sum += word.length

end

average = sum.to_i/words.size
puts "The average is " + average.to_s

You don't have to have a separate word_lengths variable to keep all the sizes of words in words array. Without looping through the word_lengths array you can merge both loops into one loop as I have given in the post.

The way you're getting the length of the word is wrong. Use word.length . See here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM