我正在开发 Head First Ruby 。这是我的代码:
class Employee
attr_reader :name
def name=(name)
end
def print_name
puts "Name: #{name}"
end
end
class SalariedEmployee < Employee
attr_reader :salary
def salary=(salary)
# code to validate and set @salary
end
def print_pay_stub
print_name
pay_for_period = (salary / 365.0) * 14
formatted_pay = format("$%.2f", pay_for_period)
puts "Pay this period: #{formatted_pay}"
end
end
class HourlyEmployee < Employee
attr_reader :hourly_wage, :hours_per_week
def hourly_wage=(hourly_wage)
# code to validate and set @hourly_wage
end
def hours_per_week=(hours_per_week)
# code to validate and set @hours_per_week
end
def print_pay_stub
print_name
pay_for_period = hourly_wage * hours_per_week * 2
formatted_pay = format("$%.2f", pay_for_period)
puts "pay This Period: #{formatted_pay}"
end
end
我无法让这项练习奏效。我收到这个错误:
employee.rb:42:in `print_pay_stub': undefined method `*' for nil:NilClass (NoMethodError)
from employee.rb:56:in `<main>'
有人可以查看这段代码并告诉我出了什么问题吗?
答案 0 :(得分:2)
编辑:我的错误 - hourly_wage
或hours_per_week
为零。确保设置好。
salary
似乎是nil
- 至少,这是*
唯一的那条线。您需要确保设置salary
编辑:澄清
编辑2:更正