Refactoring: Refactorings/Replace Loop with Collection Closure Method
Jump to navigation
Jump to search
Use a Ruby collection closure method instead of a loop when handling elements of a collection.
Mechanics
- Identify the basic pattern of the loop
- Replace the loop with the appropriate collection closure methods
- Test
Example 1
Before
managerOffices = []
employees.each do |e|
managerOffices << e.office if e.manager?
end
After
managerOffices = employees.select {|e| e.manager?}.collect {|e| e.office}
Example 2: Sum
Before
total = 0
employees.each {|e| total += e.salary}
After
total = employees.inject(0) {|sum, e| sum + e.salary}