我只是希望有人可以提供以下代码来帮助我:
def write(aFile,number)
index = 1
while (index < number)
aFile.puts(index.to_s)
index += 1
end
end
def read(aFile)
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")
if aFile
write(aFile,11)
aFile.close
else
puts "Unable to open file to write!"
end
aFile = File.new("mydata.txt","r")
if aFile
read(aFile)
aFile.close
else
puts "Unable to open file to read!"
end
end
# returns true if a string contains only digits
def is_numeric?(obj)
if /[^0-9]/.match(obj) == nil
true
end
false
end
main
我想要得到的结果是:
Line read: 0
Line read: 1
...
Line read: 10
但是我得到:
Error: first line of file is not a number
为什么会这样?我的代码一定有问题。