diff --git a/lib/6.11-replace_loop_with_collection_closure_method.rb b/lib/6.11-replace_loop_with_collection_closure_method.rb new file mode 100644 index 0000000..aefcfc3 --- /dev/null +++ b/lib/6.11-replace_loop_with_collection_closure_method.rb @@ -0,0 +1,49 @@ +class ReplaceLoopWithCollectionClosureMethod + class Company + attr_reader :employees + def initialize(employee_list) + @employees = employee_list.map{|row|Employee.new(position: row[:position], office: row[:office], salary: row[:salary])} + end + + def select_managers + managers = [] + employees.each do |e| + managers << e if e.manager? + end + return managers + end + + def employees_offices + offices = [] + employees.each {|e| offices << e.office} + return offices + end + + def manager_offices + offices = [] + employees.each do |e| + offices << e.office if e.manager? + end + return offices + end + + def total_salary + total = 0 + employees.each{|e| total += e.salary} + return total + end + end + + class Employee + attr_accessor :position, :office, :salary + def initialize(arg={}) + self.position = arg[:position] + self.office = arg[:office] + self.salary = arg[:salary] + end + + def manager? + position == 255 + end + end +end diff --git a/spec/6.11-replace_loop_with_collection_closure_method_spec.rb b/spec/6.11-replace_loop_with_collection_closure_method_spec.rb new file mode 100644 index 0000000..5606902 --- /dev/null +++ b/spec/6.11-replace_loop_with_collection_closure_method_spec.rb @@ -0,0 +1,54 @@ +require 'spec_helper' +describe ReplaceLoopWithCollectionClosureMethod do + + let(:complany_employees) { + ReplaceLoopWithCollectionClosureMethod::Company.new( + [ + { + position: 1, + office: "大阪", + salary: 100 + }, + { + position: 1, + office: "大阪", + salary: 1000 + }, + { + position: 255, + office: "東京", + salary: 10000 + } + ] + ) + + } + + describe '#select_managers' do + it 'returns only manager employee' do + expected = ReplaceLoopWithCollectionClosureMethod::Employee.new(position: 255, office: "東京", salary: 10000) + expect(complany_employees.select_managers.count).to eq 1 + expect(complany_employees.select_managers.first.position).to eq expected.position + expect(complany_employees.select_managers.first.office).to eq expected.office + expect(complany_employees.select_managers.first.salary).to eq expected.salary + end + end + + describe '#employees_offices' do + it 'returns contain 大坂 and 東京' do + expect(complany_employees.employees_offices).to eq(["大阪","大阪","東京"]) + end + end + + describe '#manager_offices' do + it 'returns contain 東京' do + expect(complany_employees.manager_offices).to eq(["東京"]) + end + end + + describe '#total_salary' do + it 'returns is 11100' do + expect(complany_employees.total_salary).to eq(11100) + end + end +end