Ruby的新手,以及一般的编程。
我正在尝试写入文件,然后将我写入的内容打印到终端中的文件中。
filename = ARGV.first
script = $0
puts "Would you like to read the file?"
puts "If you want to, hit RETURN."
puts "If you don't want to, hit CTRL+C."
prompt = "? "
STDIN.gets
puts "Opening file..."
target = File.open(filename, 'w+')
puts "Reading file..."
puts target.read()
puts "Blank, huh?"
print "Write something: "; line1 = STDIN.gets()
print "A little more: "; line2 = STDIN.gets()
target.write(line1)
target.write(line2)
puts "Let's read it now."
puts target.read()
代码一直运行,直到我到达最后一行,此时抛出以下错误:
exl16_2.rb:26:in `read': can't convert String into Integer (TypeError)
from exl16_2.rb:26:in `<main>'
不确定这意味着在我想要做的事情的背景下(打印出写的内容)。
答案 0 :(得分:0)
不确定是什么导致了您的错误,您使用的是什么Ruby版本?我试过w / 1.9和2.1并没有得到它。但是您的代码存在问题,请尝试以下方法:
filename = ARGV.first
script = $0
puts "Would you like to read the file?"
puts "If you want to, hit RETURN."
puts "If you don't want to, hit CTRL+C."
prompt = "? "
STDIN.gets
puts "Opening file..."
target = File.open(filename, 'w+')
puts "Reading file..."
puts target.read()
puts "Blank, huh?"
print "Write something: "; line1 = STDIN.gets()
print "A little more: "; line2 = STDIN.gets()
target.write(line1)
target.write(line2)
target.rewind()
puts "Let's read it now."
puts target.read()
如果您在编写后从文件中读取,它将显示为空。 rewind
调用将确保您从文件的开头读取。