I completed one of the Ruby exercism problems, Grains, using recursion. I’d love to get any feedback on my code and any possible refactorings:
The problem is to create two methods:
square, returns the number of grains on a checkerboard, which double on each square. For example, the 1st square has 1 grain, the second 2 grains, and the third 4 grains.
totalreturns the total number of grains for a square, plus all the squares before it. It defaults to all the squares on a checkboard: 64. For example, the 3rd square would return 7 grains (4+2+1).
class Grains def square(number) 2 ** (number - 1) end def total(number_of_squares=64) return 1 if number_of_squares == 1 square(number_of_squares) + total(number_of_squares - 1) end end