class Array
def sum(start = 0)
inject(start, &:+)
end
end
请解释一下这段代码的用法。 有输入和输出的测试用例会很有帮助。 谢谢。使用注入方法的Ruby代码是做什么的?
class Array
def sum(start = 0)
inject(start, &:+)
end
end
请解释一下这段代码的用法。 有输入和输出的测试用例会很有帮助。 谢谢。使用注入方法的Ruby代码是做什么的?
它总结了你阵列中的所有元素。 start
是添加了总和的值。例如对于数组foo = [1, 4]; foo.inject(10, &:+)
将返回15(10 + 1 + 4)。 &:+
告诉在数组中的每个元素上应该调用什么操作; 这是一样的,你会给你自己的回调例如
foo.inject(10) do |current_sum, current_element|
current_sum = current_sum + current_element #can be written current_sum += current_element
current_sum
end
明白了。谢谢。 – shreyanshd
FWIW'current_sum + current_element'是块体中所有必需的。 –
你问别人为你做功课吗? – elc
不,我正在看一本书,看到这段代码。作者没有给出任何代码的解释。因此,这个问题! – shreyanshd
你有没有读过[注入文档](http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-inject)并试用了代码? – mikej