Counting and computing the average length of words in ruby

时光怂恿深爱的人放手 提交于 2019-11-28 11:48:12

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/35331077/counting-and-computing-the-average-length-of-words-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!