Monday, February 3, 2014

Ruby: inject

http://ruby-doc.org/core-2.0/Enumerable.html#method-i-inject

inject( initial )  { |memo, obj|      block  }  → obj

def sum_of_cubes(a, b)
  sum = 0
  (a..b).inject(sum) { |sum, x| sum + (x*x*x) }
end

What does it do ?
-- Combines all elements of enum
-- by applying a binary operation, specified by a block

For each element in enum -
- the block is passed an accumulator value (memo) and the element
- 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.

Variation:
-------------------------
inject  { |memo, obj|     block  }  → obj

What is the initial value for 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.


No comments:

Post a Comment

Followers

Blog Archive