Ruby - Enumerable - reduce

  • + 0 comments

    Provided for clarification (hopefully):

    I understood this challenge to be asking: For a series of integers not less than 1 and through n (1..n), square the integer (i*i), add one (+1), and add to the sum (+ sum; the sum beginning at 0).

    So above, the series is 1 through n. Starting at a base of 0 (the beginning sum) you perform the operation {sum + (i^2 + 1)}.

    The inject/reduce method keeps track of the sum and returns the final sum at the end.

    Solution:

    def sum_terms(n)
      # your code here
        (1..n).inject(0) {|sum, i| sum + (i*i + 1) }
    end
    

    (1..n) # series of integers

    .inject(0) # inject/reduce method with base 0

    {|sum, i| # elements to be used in operation

    sum + (i*i + 1) } # operation