Improve problem 8 solution in ruby