【问题标题】:`-': nil can't be coerced into Fixnum (TypeError)`-': nil 不能被强制转换为 Fixnum (TypeError)
【发布时间】:2010-08-04 15:19:46
【问题描述】:

在我的程序中,我收到一个错误,上面写着 ./ruby_camping.rb:91:in `-': nil can't be coerced into Fixnum (TypeError)。我想做的是结帐我刚刚签到的客人。这是结帐部分的代码块:

def self.check_out 
  puts "Welcome to checkout!"
  puts $camping.current_guests
  puts " Here are the current guests, who do you want to checkout?!" 
  puts "State plot number "
  plot = gets.chomp.to_i
  guest = $camping.current_guests[plot-1] 
  puts "State the date for your checkout (a number bigger then " + guest.arrived.to_s + "): "
  # it should not be possible for a guest to checkout before she has checked in
  departureDate = gets.chomp.to_i
  guestStayedDays = departureDate - guest.arrived #Days the guest has stayed
  while (guestStayedDays < 1) do                        
   puts "The date for checkout is not valid. The guest checked in " + guest.arrived.to_s
   puts "Please state a new date."
   departureDate = gets.chomp.to_i
   guestStayedDays = departureDate - guest.arrived
  end       
  guest.departure = departureDate
  guest.plot.increase(guestStayedDays) # increases the electricity meter
  puts guest # prints the guest
  $camping.current_guests[plot-1] = nil # emptys the plot
 end
end

departmentDate怎么还是nil呢?感谢您的帮助!

【问题讨论】:

    标签: ruby


    【解决方案1】:

    要获得更详细的答案,您必须在程序中指出哪一行是第 91 行。但是,要指出正确的方向,如果您看到的是nil can't be coerced into Fixnum,那么这意味着-右侧nil。例如

    irb(main):001:0> 5 - nil
    TypeError: nil can't be coerced into Fixnum
            from (irb):1:in `-'
            from (irb):1
    

    从你的代码中我能看到的唯一可能的例子是guestStayedDays = departureDate - guest.arrived,所以我会检查guest.arrived的值。

    如果-左侧nil,例如departureDateplot 那么你会得到 undefined method '-' for nil:NilClass

    【讨论】:

    • 是的,你是正确的第 91 行指向:guestStayedDays = leaveDate - guest.arrived。你的回答证实了我的怀疑。那么我想这个值一定是零?
    • 正确。从您看到的错误来看,它必须是guest.arrived,即nilguest 不是nil,因为您成功地调用了arrived,而departureDate 不是nil,因为您成功地调用了-。这是- 的论点(guest.arrived 这就是问题所在。)
    • 感谢 mikej 的回答。我会试试看能不能解决这个问题。
    • 如果您将完整程序的副本通过电子邮件发送给我(my profile 中的详细联系信息)以及获取错误的步骤,我会快速查看。然后,我们可以编辑问题以添加相关详细信息,以防将来其他人感兴趣。
    • 这个答案也有帮助。谢谢迈克。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多