Ruby在写入行后打印空白

时间:2015-10-05 13:06:36

标签: ruby

我正在尝试截断并在文件内容中写入新行,然后将其打印出来:

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保持打印空白。我写的文本文件包含我输入的文本。我不确定发生了什么。

1 个答案:

答案 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