打印

[标准问题] 变格式吗? 有一题怎么也跑不出来

变格式吗? 有一题怎么也跑不出来

有一题怎么也跑不出来。

Make a program that outputs the sum of all the comma separated values in the
string "1,2,3,4,5,6,7,8,9,10".

填空:
str = "1,2,3,4,5,6,7,8,9,10"
s = str.split(/,/)
sum = (1)
(2) .each { |i|
sum = sum + (3)
}
puts "Sum: #{sum}"

我的答案都是: (1)0 (2)s (3)i   可是我无论如何也跑不出来。结果是
rb48E.tmp:18:in `+': String can't be coerced into Fixnum (TypeError)
    from C:/DOCUME~1/XIANGY~1/LOCALS~1/Temp/rb48E.tmp:18
    from C:/DOCUME~1/XIANGY~1/LOCALS~1/Temp/rb48E.tmp:17:in `each'
    from C:/DOCUME~1/XIANGY~1/LOCALS~1/Temp/rb48E.tmp:17
Complete(1)

不知道怎么改。请牛牛指教。(前提是只能填这三个空) 多谢, 我是php?name=Ruby" onclick="tagshow(event)" class="t_tag">Ruby。1.8.6

TOP

split分出来的数组里面的元素都是字符串。
而你将他们和一个数字相加,于是就出现了如下错误
(1)0
(2)s
(3)i.to_i
就可以了

另对数组迭代求和也可以写成这样
sum = s.inject { |sum, i| sum+i.to_i }
Digging ruby with Pickaxe,
Running agilely on rails

TOP

2008-11-21 00:18 Crawled by CCBot/1.0 (+http://www.commoncrawl.org/bot.html) @38.103.63.61