私有方法`得到'调用(NoMethodError)Ruby

时间:2017-02-18 00:44:56

标签: ruby error-handling nomethoderror

获取错误

 "private method `gets' called for `ot,Room 203,Healthcare Info Session,2014,6,17,14,0\n":String (NoMethodError)"

并且不确定我的代码在哪里出错。

appointments.txt中的第一行:

ot,Room 203,Healthcare Info Session,2014,6,17,14,0

有人可以告诉我代码中需要更改的内容:

appointments = [ ]
file_object = File.open("appointments.txt", "r")

while line = file_object.gets
  fields = line.gets.chomp.split(',')
  appointment_type = [0]

  if appointment_type == 'ot'
    location = fields[1]
    purpose = fields[2]
    year = fields[3].to_i
    month = fields[4].to_i
    day = fields[5].to_i
    hour = fields[6].to_i
    minute = fields[7].to_i
    appt1 = OneTimeAppointment.new("Dentist", "Cleaning", 4, 45, 5, 20, 2017)
    appointments.push(appt1)
  else 
    location = fields[1]
    purpose = fields[2]
    hour = fields[3].to_i
    minute = fields[4].to_i
    day = fields[5].to_i
    appt2 = MonthlyAppointment.new("Doctor", "Cold", 2, 30, 15)
    appointments.push(appt2)
  end  
end

1 个答案:

答案 0 :(得分:1)

您无法在字符串上调用gets。您在文件上调用gets来检索该行,但是出于某种原因您可以在该行上调用gets。这是不正确的。

修复如下:

File.readlines('appointments.txt') do |line|
  fields = line.chomp.split(',')

  # ...
end

如果您正在阅读CSV数据,则可能需要考虑使用Ruby附带的CSV library

相关问题