used each_with_object to refactor