gpt4 book ai didi

ruby - 无法显示 read()

转载 作者:太空宇宙 更新时间:2023-11-03 16:52:54 26 4
gpt4 key购买 nike

下面是我的代码,它似乎运行良好并按预期写入文件。但是,我根本无法获得第 45 行,puts target.read(),以显示 target 的内容。请帮忙。哦,对于我的代码其他部分的任何其他批评或建议也将不胜感激。

filename = ARGV.first
script = $0

puts "We're going to erase #{filename}."
puts "If you don't want that, hit CTRL-C."
puts "If you do want that, hit RETURN."

print ">>"
STDIN.gets

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

puts "Truncating the file."
target.truncate(target.size)

puts "Now, I'm going to ask for you 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'm 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 "Do you want to continue and perform the same"
puts "task with one line of target.write() methods?"
puts "Give me a 'yes' or a 'no'."
print ">>"
answer = STDIN.gets.chomp()
puts "=============================="
if answer == "yes"
target.write("#{line1}\n#{line2}\n#{line3}\n")
end

puts "This is the content of #{filename}:\n"
target = File.open(filename)
# Cannot figure out why the program is not displaying the contents
# of the target file when it's run.
puts target.read()
puts "And finally, we close it."
target.close()

最佳答案

你应该打开 target 阅读:

target = File.open(filename, 'r')

根据文档,read采用整数参数作为要读取的字节数。相反,我建议使用迭代方法并逐行打印。您之前也不必打开文件,但我想我还是会在打开时向您展示“r”参数。

这是我会做的:

IO.foreach(filename) do |line|
puts line
end

此方法会在 block 完成后关闭文件,因此无需显式调用 close。不过,在阅读之前,请确保在写入文件后关闭该文件。

关于ruby - 无法显示 read(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17013588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com