Ruby implementation of a possible solution