Ad

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
    • def sum n
    • return 1 if n == 1 # Base case of recursion method - must be defined; otherwise infinite recursion may occur
    • n + sum(n - 1)
    • raise ArgumentError('n must be greater than 0') if n < 1
    • n == 1 ? 1 : n + sum(n - 1)
    • end