← Back to Upcase

Feedback on Ruby exercise


(Paul Haddad) #1

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:

  1. 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.

  2. total returns 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

(Andy Waite) #2

I would apply the Replace Magic Number with Symbolic Constant refactoring on the 64 literal.


(Paul Haddad) #3

Thanks, @andyw8! That’s a good refactor.