Solved problem 6 in Ruby