这个练习有问题

时间:2016-06-22 17:23:21

标签: ruby

我正在开发 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>'

有人可以查看这段代码并告诉我出了什么问题吗?

1 个答案:

答案 0 :(得分:2)

编辑:我的错误 - hourly_wagehours_per_week为零。确保设置好。

salary似乎是nil - 至少,这是*唯一的那条线。您需要确保设置salary

编辑:澄清

编辑2:更正