Back

reduce/inject 方法的用法( the usage of reduce/inject in Ruby)

发布时间: 2013-12-03 02:15:00

用了5年RUBY了,今天居然头一回遇到这个情况:   需要对某个数组中的所有操作进行   的操作。 ( For the past years, I have not met this kind of questions until this morning, I need to loop all the elements of an array and return an result: )

current_element.product(next_element)

搜索了一下, 应该使用 reduct/inject 方法.  ( after googling around, I found I should use the method: inject/reduce )

some_array = [1,2,3]
some_array.inject(0) { |memo, n| memo = memo + n}  # => 0+6 = 6
see: http://stackoverflow.com/questions/1538789/how-to-sum-array-members-in-ruby

Back