Menu
Coddy logo textTech

Recap - Staff Payroll

Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 26 of 57.

challenge icon

Challenge

Medium

Build a payroll with inheritance. Employee.new(name, rate) has pay(hours) (rate times hours, with hours above 40 paid at 1.5 times the rate) and line(hours) returning Ada (employee): 800.00, built from pay(hours) and role, where role returns employee. Manager.new(name, rate, bonus) passes name and rate to super, adds the bonus to super's pay and has the role manager. Contractor < Employee is paid rate times hours with no overtime and has the role contractor.

The supplied code reads lines employee Ada 20 40, manager Bo 30 45 500 or contractor Cy 50 50 (name, rate, hours, and a bonus for managers) and prints line(hours) for each, then staff: 3, managers: 1, employees: 3 (both counted with is_a?, so managers and contractors are employees too) and the total pay.

Your code goes in employee.rb, manager.rb and contractor.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'employee'
require_relative 'manager'
require_relative 'contractor'

# Supplied input/output code: keep it as it is
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) })

All lessons in Object Oriented Programming

Practice on your own: Online Ruby compiler