计算和计算红宝石中单词的平均长度 [英] Counting and computing the average length of words in ruby

查看:105
本文介绍了计算和计算红宝石中单词的平均长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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?

推荐答案

尝试:

words.join.length.to_f / words.length

说明:

这一起利用了 chaining 方法.首先,words.join给出了数组中所有字符的字符串:

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

'Fourscoreandsevenyearsagoourfathersbroughtforthonthiscontinentanewnationconcei
vedinLibertyanddedicatedtothepropositionthatallmenarecreatedequal'

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

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

143.0

然后使用/ words.length将以上内容相除:

We then divide the above using / words.length:

4.766666666666667

这篇关于计算和计算红宝石中单词的平均长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆