Кажется, я не могу прочитать мои данные как целое число и распечатать их. плюс есть функция закрытия потока (IOError) для count = aFile.gets в функции def read (afile). Эта программа включает в себя массив, файлы и циклы. Цель этой программы состоит в том, чтобы взять число 10 и записать число в файл, а затем в каждой строке с шагом от 0 до 10.
# takes a number and writes that number to a file then on each line
# increments from zero to the number passed
def write(aFile, number)
# You might need to fix this next line:
aFile.puts("number")
index = 0
while (index < number)
aFile.puts(number.to_s)
index += 1
end
end
# Read the data from the file and print out each line
def read(aFile)
# Defensive programming:
count = aFile.gets
if (is_numeric(count))
count = count.to_i
else
count = 0
puts "Error: first line of file is not a number"
end
index = 0
while (count < index)
line = aFile.gets
puts "Line read: " + line
end
end
# Write data to a file then read it in and print it out
def main
aFile = File.new("mydata.txt", "w") # open for writing
if aFile # if nil this test will be false
write(aFile, 10)
else
puts "Unable to open file to write!"
end
if aFile
read(aFile)
end
aFile.close
end
# returns true if a string contains only digits
def is_numeric?(obj)
if /[^0-9]/.match(obj) == nil
true
end
false
end
main
2 ответа
Если вы хотите, чтобы ваш код работал, измените:
aFile = File.new("mydata.txt", "w")
Чтобы :
aFile = File.new("mydata.txt", "r+")
Ты можешь измениться:
count = aFile.gets
if (is_numeric(count))
Чтобы :
count = aFile.gets.to_i
if (count.is_a?(Fixnum))
А затем избавиться от метода is_numeric?(obj)
.
Также вы не увеличиваете счетчик, вы также можете это исправить.
Вот работающий скин-код, вы легко добавите функции, которые я удалил.
def write(a_file, number)
(1..number).each { |n| a_file.puts(n) }
end
def read(a_file)
a_file.each { |line| puts line }
end
def main
a_file = File.new("mydata.txt", "w")
if a_file
write(a_file, 10)
else
puts "Unable to open file to write!"
end
a_file.close
a_file = File.open("mydata.txt", "r")
if a_file
read(a_file)
end
a_file.close
end
main
Основные ошибки, которые я нашел:
- После записи закройте файл и снова откройте для записи
- Смотрите здесь для чтения: Что все распространенные способы чтения файлов в Ruby?
aFile.puts(number.to_s)
вы должны поставитьindex
, который является возрастающей переменной(is_numeric(count))
отсутствует?
Примечание: используйте нотацию Ruby для переменных: a_file
- это хорошо, aFile
- нет.
Новые вопросы
ruby
Ruby - это многоплатформенный динамический объектно-ориентированный интерпретируемый язык с открытым исходным кодом. Тег [ruby] предназначен для вопросов, связанных с языком Ruby, включая его синтаксис и его библиотеки. Вопросы Ruby on Rails должны быть помечены [ruby-on-rails].