'NoMethodError: private method `gets' called for "test.txt":String

I encountered the error "NoMethodError: private method `gets' called for "test.txt":String" when doing my code:

def write_data_to_file(mydata)
   mydata << ("5\n")
   mydata << ("Fred\n")
   mydata << ("Sam\n")
   mydata << ("Jill\n")
   mydata << ("Jenny\n")
   mydata << ("Zorro")
end

def read_data_from_file(mydata)
  count = mydata.gets.to_i()
  i = 0
  while (i <= count)
    puts mydata.gets
    i += 1
  end
end

def main()
  mydata = File.new("mydata.txt", "w") # open for writing
  write_data_to_file(mydata)
  mydata.close()
  
  mydata = File.open("mydata.txt", "r") # open for reading
  read_data_from_file(mydata)
  mydata.close()
end

main()

Currently, I want to use the first line that contains 5 to convert it into an integer to use as a control variable. Please enlighten me why I encountered this error and how to fix it. Thank you!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source