We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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:
defsum_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
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Ruby - Enumerable - reduce
You are viewing a single comment's thread. Return to all 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:
(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