moonprince 2008-8-10 20:54
变格式吗? 有一题怎么也跑不出来
有一题怎么也跑不出来。
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)
不知道怎么改。请牛牛指教。(前提是只能填这三个空) 多谢, 我是Ruby。1.8.6
xavier 2008-8-11 08:24
split分出来的数组里面的元素都是字符串。
而你将他们和一个数字相加,于是就出现了如下错误
(1)0
(2)s
(3)i.to_i
就可以了
另对数组迭代求和也可以写成这样
sum = s.inject { |sum, i| sum+i.to_i }