I'd give people access to their language's output facility for playing around to the solution, but that is a minor nitpick. (And I suppose I could open an irb instance on my machine for exploration and then give you code when I'm good and ready.)
My Ruby solution, in case we've got anybody who is struggling: http://pastie.org/771438 This would be my first cut if you asked me to whiteboard this.