[英]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.