Functional and Recursive Ruby

This program returns Squares. From a functional perspective, the use of a variable for the ‘range_object’ is technically a side-effect, but I include it here for sake of clarity.

Range objects are a good example of the kind syntactic sugar that I sometimes felt was lacking in JavaScript.

class Squares
  def initialize(n)
    @number = n
  end

  def square_of_sum
    def factorial(n)
      n == 1 ? 1 : n + factorial(n - 1)
    end

    factorial(@number) ** 2
  end

  def sum_of_squares
    range_object = 1..@number
    range_object.reduce { | a, b | a + b ** 2 }
  end

  def difference
    square_of_sum - sum_of_squares
  end
end