=20
I was wondering why these are equivalent:
=20
a=3D(1..100).inject :+
b=3D(1..100).inject 0, :+
=20
but these aren't
=20
%w/lib1 lib2 lib3/.inject :require
%w/lib1 lib2 lib3/.inject 0, :require
1887 % ri Enumerable.inject
=3D Enumerable.inject
(from ruby core)
=
--------------------------------------------------------------------------=
----
enum.inject(initial, sym) =3D> obj
enum.inject(sym) =3D> obj
enum.inject(initial) {| memo, obj | block } =3D> obj
enum.inject {| memo, obj | block } =3D> obj
=
--------------------------------------------------------------------------=
----
enum.reduce(initial, sym) =3D> obj
enum.reduce(sym) =3D> obj
enum.reduce(initial) {| memo, obj | block } =3D> obj
enum.reduce {| memo, obj | block } =3D> 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<i>
the block is passed an
accumulator value
(<i>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 fo the method.
If you do not explicitly specify an initial value for
memo, then uses the first element of collection is used as the initial
value of memo.
Examples:
# Sum some numbers
(5..10).reduce
+) #=3D> 45
# Same using a block and inject
(5..10).inject {|sum, n| sum + n } #=3D> 45
# Multiply some numbers
(5..10).reduce(1, :*) #=3D> 151200
# Same using a block
(5..10).inject(1) {|product, n| product * n } #=3D> 151200
# find the longest word
longest =3D %w{ cat sheep bear }.inject do |memo,word|
memo.length > word.length ? memo : word
end
longest #=3D> "sheep"