API里面这样写
reduce(initial, sym) → obj reduce(初始值,符号)
reduce(sym) → obj reduce(符号)
reduce(initial) { |memo, obj| block } → obj reduce(初始值){ |memo , 对象| 块}
reduce { |memo, obj| block } → obj reduce{ |memo, 对象| 块}
Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.
由块或符号命名的一个方法或者操作,通过执行一个二进制操作,将所有枚举的元素结合起来
If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element. If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method.
如果你指定了一个块,那么集合里的每个元素被传递给一个收集器(memo,这里是一个元素)里存放的值。如果你指定的是一个符号,那么每个元素将会被传递给一个memo(这时是一个方法)。无论用哪种方法,结果都会变成memo里存放的新值。迭代到最后,memo的将值返回给方法。
If you do not explicitly specify an initial value for memo, then the first element of collection is used as the initial value of memo.
如果你未明确初始化memo的值,那么memo将会被赋值为集合内的第一个元素。
通过上面的理解,我们知道memo就是用来存放结果值的一个值或者方法。
# Sum some numbers 累加 (5..10).reduce(:+) #=> 45 #(5..10).reduce(符号) # Same using a block and inject 累加 (5..10).inject { |sum, n| sum + n } #=> 45 #(5..10).inject{ |memo, 对象| 块 } # Multiply some numbers 阶乘 (5..10).reduce(1, :*) #=> 151200#(5..10).redeuce(初始值,符号) # Same using a block 阶乘 (5..10).inject(1) { |product, n| product * n } #=> 151200#(5..10).inject(初始值){ |memo , 对象| 块} # find the longest word longest = %w{ cat sheep bear }.inject do |memo, word| memo.length > word.length ? memo : word endlongest #=> "sheep"#这个也是利用块,我们可以把代码加上{} longest = %w{ cat sheep bear }.inject { |memo, word| memo.length > word.length ? memo : word }#现在很好理解了,其实是一个道理,可以这么用就是,理解了这个用法,对写程序的能力提高很大的帮助,%w的意思是将{ cat sheep bear }变为["cat", "sheep", "bear"]。
看到例子中用了inject方法,我们再来看看inject方法是怎么介绍的
去查了下,API里面的介绍相同,如下
inject(initial, sym) → obj
inject(sym) → obj
inject(initial) { |memo, obj| block } → obj
inject { |memo, obj| block } → obj
Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.
If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element. If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method.
If you do not explicitly specify an initial value for memo, then the first element of collection is used as the initial value of memo.