2013-04-04 193 views
0

我想用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) 

我究竟做错了什么?

+0

的http://stackoverflow.com/questions/1538789/how-to-sum-array-members-in-ruby?rq=1 – 2013-04-04 17:31:25

回答

2

你不应该使用这个map/collectreduce/inject是适当的方法

def sum(a) 
    a.reduce(:+) 
    # or full form 
    # a.reduce {|memo, el| memo + el } 

    # or, if your elements can be strings 
    # a.map(&:to_i).reduce(:+) 
end 
+0

对于像'a = [“123”,“23”,“345”,“678”]''这样的数组,这是失败的。我认为Mike F特别使用'.to_i'。 – 2013-04-04 17:34:28

+0

@JoeFrambach:谢谢,错过了。 – 2013-04-04 17:35:44

+0

“a.map(&:to_i).reduce(:+)”如何在大型数组上使用内存使用?它会使内存使用量翻倍吗,还是Ruby能够更聪明地做到这一点? – 2013-04-04 17:37:52