繁体   English   中英

计算和计算红宝石中单词的平均长度

[英]Counting and computing the average length of words in ruby

我正在尝试用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

显然,该代码无法正常工作。 当我运行程序时,我收到一条错误消息,提示不能将字符串'+'强制转换为fixnum(typeerror)。

我该怎么办才能使代码不计算数组中字符串的平均长度?

尝试

words.join.length.to_f / words.length

说明:

这利用了链接方法在一起的优势。 首先, words.join给出了字符串中所有字符的字符串:

'Fourscoreandsevenyearsagoourfathersbroughtforthonthiscontinentanewnationconcei
vedinLibertyanddedicatedtothepropositionthatallmenarecreatedequal'

然后,我们应用length.to_f给出长度作为浮点数(使用浮点数可确保获得准确的最终结果):

143.0

然后,我们使用/ words.length划分以上/ words.length

4.766666666666667

尝试这个。

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

您不必具有单独的word_lengths变量即可将所有大小的单词保留在words数组中。 无需循环遍历word_lengths数组,就可以将两个循环合并为一个循环,就像我在文章中给出的那样。

您得到word长度的方式是错误的。 使用word.length 这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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