Rubyでサムオブスクエアスクエアオブサム 〜Rubyでオイラープロジェクトを解こう!Problem6

Problem 6 - Project Eulerより

The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
最初の10個の自然数を二乗したものの合計は、
1^2 + 2^2 + ... + 10^2 = 385
最初の10個の自然数の合計を二乗したものは、
(1 + 2 + ... + 10)^2 = 55^2 = 3025
よってこれらの差は、3025 - 385 = 2640である。
最初の100個の自然数を二乗したものの合計と、それら自然数の合計を二乗したものとの差を求めよ。

 def sum_of_squares(limit)
   sum = 0
   1.upto(limit) do |n|
     sum += n ** 2
   end
   sum
 end

 def square_of_sum(limit)
   (1..limit).to_a.inject(:+) ** 2
 end

 limit = 100
 (sum_of_squares(limit) - square_of_sum(limit)).abs # => 25164150