Counting and computing the average length of words in ruby

守給你的承諾、 提交于 2019-11-29 18:02:01

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.

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