After thinking about the problem, a much more optimized solution in Ruby