私有方法"gets"调用(NoMethodError)Ruby



获取错误

 "private method `gets' called for `ot,Room 203,Healthcare Info Session,2014,6,17,14,0n":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

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

修复看起来像这样:

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

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

最新更新