我想用ruby编写一个小函数,该函数从用户获取一个数组,然后总结数组中的数据。我已经写它作为红宝石数组输入
def sum(a)
total = 0
a.collect { |a| a.to_i + total }
end
然后,该函数贯穿一个rspec的,其通过最初供给到它空白阵列测试它。这这将导致以下错误
sum computes the sum of an empty array
Failure/Error: sum([]).should == 0
expected: 0
got: [] (using ==)
因此,它告诉我,当它在,喂空数组它应该得到0,而是其得到阵列。我试图把一个if语句写成
,但它给了我一个错误说
syntax error, unexpected '}', expecting => (SyntaxError)
我究竟做错了什么?
的http://stackoverflow.com/questions/1538789/how-to-sum-array-members-in-ruby?rq=1 – 2013-04-04 17:31:25