Ruby读写文件
我有下面的代码。为了使代码正常工作,应该读取这些行并将它们写入控制台。我目前只得到一个错误:文件的第一行不是数字 任何可能的帮助都会很好Ruby读写文件,ruby,Ruby,我有下面的代码。为了使代码正常工作,应该读取这些行并将它们写入控制台。我目前只得到一个错误:文件的第一行不是数字 任何可能的帮助都会很好 def write(aFile, number) aFile.puts(number) index = 0 while (index <= number) aFile.puts(index) index += 1 end end def read(aFile) count = aFile.gets if (i
def write(aFile, number)
aFile.puts(number)
index = 0
while (index <= number)
aFile.puts(index)
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
index += 1
end
end
def main
aFile = File.new("mydata.txt", "w")
if aFile
write(aFile, 10)
aFile.close
aFile = File.new("mydata.txt", "r")
read(aFile)
aFile.close
else
puts "Unable to open file to write or read!"
end
end
def is_numeric?(obj)
if /[^0-9]/.match(obj) == nil
true
end
false
end
main
请检查以下内容:
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
读取文件行时,始终读取文件中文本/字符串偶数的行。所以你总是在else块中。检查我在答案中发布的原因,我将根据你的预期输出进行更新以给出结果。提示:s in get代表什么?第二个提示:它不代表数字!这是数字吗?总是返回false。这是数字吗?对于此方法的名称来说,这不是一个好的选择,因为您只是在测试字符串是否包含正则表达式可以为/\d/的数字。假设希望字符串表示一个非负整数,则可以编写:def nni?str str.match?/\a\d+\z/end。