在写完文件后读取文件

时间:2018-02-22 17:44:57

标签: ruby

我在learnrubythehardway.org正在exercise 16
文件名作为参数传递给以下脚本,该脚本要求用户在文件中写入三行:

filename = ARGV.first

puts "Opening the file..."
target = open(filename, 'w+')

puts "Now I am going to ask you for three lines."
print "line 1: "
line1 = $stdin.gets.chomp
print "line 2: "
line2 = $stdin.gets.chomp
print "line 3: "
line3 = $stdin.gets.chomp

puts "I am going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

puts "Here is your new file:"
print target.read

puts "And finally we close it"
target.close

在关闭文件之前,我希望用户有机会看到新文件的内容,但不会处理该部分代码。那是为什么?

1 个答案:

答案 0 :(得分:2)

如果你想阅读你刚刚写的内容,你必须rewind该文件。

target.write(line3)
target.write("\n")

target.rewind
target.read 

奖金内容

使用puts,它会为您编写换行符。

target.puts(line3)