Earn extra honor and gain new allies!
Honor is earned for each new codewarrior who joins.
Learn more

Use a recursive method to calculate the sum of all integers from 1 to n.

An ArgumentError should be raised if the input is below 1.

Code
Diff
  • def sum n
      raise ArgumentError('n must be greater than 0') if n < 1
      n == 1 ? 1 : n + sum(n - 1)
    end
  • 11 def sum n
    2- return 1 if n == 1 # Base case of recursion method - must be defined; otherwise infinite recursion may occur
    3- n + sum(n - 1)
    2+ raise ArgumentError('n must be greater than 0') if n < 1
    3+ n == 1 ? 1 : n + sum(n - 1)
    44 end