红宝石数组输入
我想用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)
我究竟做错了什么?
在这里看到:How to sum array of numbers in Ruby?
这里:http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-inject
def sum(a)
array.inject(0) {|sum,x| sum + x.to_i }
end
这个工作重复, 谢谢。它是否工作,因为它告诉程序如果该位置是空白,则将零添加到每个位置? – 2013-04-05 01:28:35
它将每个位置转换为一个整数。如果它是空白的,那么它将转换为零。 – 2013-04-05 01:52:19
你不应该使用这个map
/collect
。 reduce
/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
对于像'a = [“123”,“23”,“345”,“678”]''这样的数组,这是失败的。我认为Mike F特别使用'.to_i'。 – 2013-04-04 17:34:28
@JoeFrambach:谢谢,错过了。 – 2013-04-04 17:35:44
“a.map(&:to_i).reduce(:+)”如何在大型数组上使用内存使用?它会使内存使用量翻倍吗,还是Ruby能够更聪明地做到这一点? – 2013-04-04 17:37:52
gets.split.map(&:to_i).inject(:+)
的http://*.com/questions/1538789/how-to-sum-array-members-in-ruby?rq=1 – 2013-04-04 17:31:25