refactoring replacing while by each