【问题标题】:Counting and computing the average length of words in ruby计算和计算 ruby​​ 中单词的平均长度
【发布时间】:2016-05-21 17:48:21
【问题描述】:

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

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

【问题讨论】:

  • 什么是word_tos 是什么? length 是什么?

标签: arrays ruby string average


【解决方案1】:

试试

words.join.length.to_f / words.length

说明:

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

'Fourscoreandsevenyearsagoourfathersbroughtforthonthiscontinentanewnationconcei
vedinLibertyanddedicatedtothepropositionthatallmenarecreatedequal'

然后我们应用length.to_f 将长度作为浮点数(使用浮点数确保最终结果准确):

143.0

然后我们使用/ words.length来划分上述内容:

4.766666666666667

【讨论】:

  • 也可以使用fdiv得到浮点结果:words.join.length.fdiv(words.length)
【解决方案2】:

试试这个。

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。见here

【讨论】:

  • 由于用户是新用户,能否请您添加cmets。他的问题在于数组的功能。请解释数组字的功能。例如 word.length 与使用 word.size 之类的东西来计算平均值。由于他是新人,并且由于他在“do”循环中选择的命名约定,因此并不直观。
  • @Bunti 谢谢!你是救生员!
  • 首选sum = words.reduce(0) {|sum, word| sum + word.length }
  • @Jordan reducemap 配合得很好,例如words.map(&amp;:length).reduce(:+)
  • @Stefan 确实如此,尽管如果可以避免的话,我会反射性地避免多次迭代相同的数据结构。但是,在这种情况下(使用如此小的数组)并没有什么区别,而且您的版本很好且可读,所以 ?。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
相关资源
最近更新 更多