我正在尝试截断并在文件内容中写入新行,然后将其打印出来:
target = File.open(ARGV.first, 'w')
puts "we are going to clear the file first"
target.truncate(0)
puts "give me 1 line"
line1 = $stdin.gets.chomp
puts "give me another line!"
line2 = $stdin.gets.chomp
puts "we are gonna write the text into the file now"
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
newfile = open(ARGV.first, 'r')
puts newfile.read
puts "we will close the file now"
target.close
然而,Ruby保持打印空白。我写的文本文件包含我输入的文本。我不确定发生了什么。
答案 0 :(得分:1)
在尝试阅读文件之前,您需要关闭该文件。
target = File.open(ARGV.first, 'w')
puts "we are going to clear the file first"
target.truncate(0)
puts "give me 1 line"
line1 = $stdin.gets.chomp
puts "give me another line!"
line2 = $stdin.gets.chomp
puts "we are gonna write the text into the file now"
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
puts "we will close the file now"
target.close
newfile = open(ARGV.first, 'r')
puts newfile.read