【发布时间】: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_to?s是什么?length是什么?
标签: arrays ruby string average