回顾:员工薪资
本课属于 Coddy Ruby 学习旅程的“面向对象编程”单元。第 26 课,共 57 课。
挑战
中等使用继承构建工资系统。Employee.new(name, rate) 有 pay(hours)(工资按时薪乘以工时计算,超过 40 小时的部分按 1.5 倍时薪计算),还有 line(hours),它返回 Ada (employee): 800.00,由 pay(hours) 和 role 构成,其中 role 返回 employee。Manager.new(name, rate, bonus) 将 name 和 rate 传给 super,在 super 的工资上加上奖金,角色为 manager。Contractor < Employee 的工资按时薪乘以工时计算,不计算加班费,角色为 contractor。
提供的代码会读取以下行:employee Ada 20 40、manager Bo 30 45 500 或 contractor Cy 50 50(分别包含姓名、时薪、工时,以及经理的奖金),并为每个人打印 line(hours),然后打印 staff: 3, managers: 1, employees: 3(两者都使用 is_a? 计数,因此经理和承包商也属于员工)和总工资。
你的代码写在 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 在线编译器