[英]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. 我正在尝试用ruby调试程序,该程序用于计算和打印数组中单词的平均长度。
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).
当我运行程序时,我收到一条错误消息,提示不能将字符串'+'强制转换为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: 首先,
words.join
给出了字符串中所有字符的字符串:
'Fourscoreandsevenyearsagoourfathersbroughtforthonthiscontinentanewnationconcei
vedinLibertyanddedicatedtothepropositionthatallmenarecreatedequal'
We then we apply length.to_f
giving the length as a float (using a float ensures an accurate final result): 然后,我们应用
length.to_f
给出长度作为浮点数(使用浮点数可确保获得准确的最终结果):
143.0
We then divide the above using / words.length
: 然后,我们使用
/ words.length
划分以上/ 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. 您不必具有单独的
word_lengths
变量即可将所有大小的单词保留在words
数组中。 Without looping through the word_lengths
array you can merge both loops into one loop as I have given in the post. 无需循环遍历
word_lengths
数组,就可以将两个循环合并为一个循环,就像我在文章中给出的那样。
The way you're getting the length of the word
is wrong. 您得到
word
长度的方式是错误的。 Use word.length
. 使用
word.length
。 See here . 看这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.