복습 - 직원 급여
Coddy Ruby 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 26번째.
챌린지
중급상속을 사용하여 급여 계산기를 만드세요. Employee.new(name, rate)에는 pay(hours)(rate에 hours를 곱하며, 40을 초과하는 hours에는 rate의 1.5배를 지급)와 line(hours)이 있으며, 이는 pay(hours)와 role을 사용하여 Ada (employee): 800.00을 반환합니다. 여기서 role은 employee를 반환합니다. Manager.new(name, rate, bonus)는 name과 rate를 super에 전달하고, super의 급여에 bonus를 더하며 manager 역할을 가집니다. Contractor < Employee는 초과 근무 수당 없이 rate에 hours를 곱한 금액을 받고 contractor 역할을 가집니다.
제공된 코드는 employee Ada 20 40, manager Bo 30 45 500 또는 contractor Cy 50 50(name, rate, hours, 그리고 manager의 bonus) 형식의 줄을 읽고 각각에 대해 line(hours)를 출력한 다음, staff: 3, managers: 1, employees: 3을 출력합니다(is_a?를 사용하여 둘 다 계산하므로 manager와 contractor도 employee에 포함됩니다). 마지막으로 총 급여를 출력합니다.
코드는 employee.rb, manager.rb 및 contractor.rb에 작성합니다. main.rb에는 제공된 입력/출력 코드가 들어 있으며 편집할 수 없습니다.
직접 해보기
require_relative 'employee'
require_relative 'manager'
require_relative 'contractor'
# 제공된 입력/출력 코드: 그대로 유지하세요
input = []
while (line = gets)
input << line.chomp
end
staff = input.map do |line|
kind, name, rate, hours, bonus = line.split
worker = case kind
when "manager" then Manager.new(name, rate.to_f, bonus.to_f)
when "contractor" then Contractor.new(name, rate.to_f)
else Employee.new(name, rate.to_f)
end
[worker, hours.to_i]
end
staff.each { |worker, hours| puts worker.line(hours) }
managers = staff.count { |w, _| w.is_a?(Manager) }
employees = staff.count { |w, _| w.is_a?(Employee) }
puts "staff: #{staff.size}, managers: #{managers}, employees: #{employees}"
puts format("total: %.2f", staff.sum { |w, h| w.pay(h) })
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Ruby 컴파일러