Refactor code to use for each