0

尝试使用 target.write 将 5 行减少到 1 时出现上述错误:

target.write("%s \n %s \n %s \n") % [line1, line2, line3]
# target.write("\n")
# target.write(line2)
# target.write("\n")
# target.write(line3)
# target.write("\n")

注释部分运行(当第一行是target.write(line1),但这不是。

为什么第一行与写出注释掉的六行不同?这是整个脚本:

filename = ARGV.first
script = $0

puts "We're going to erase #{filename}."
puts "If you don't want that hit control C"
puts "If you do want that hit execute or return"

print "? "
STDIN.gets

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

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

puts "Now I'm going to ask you for three lines."

print "line1: "; line1 = STDIN.gets.chomp()
print "line2: "; line2 = STDIN.gets.chomp()
print "line3: "; line3 = STDIN.gets.chomp()

puts "I'm going to write these to the file."

target.write("%s \n %s \n %s \n") % [line1, line2, line3]
# target.write("\n")
# target.write(line2)
# target.write("\n")
# target.write(line3)
# target.write("\n")

puts "And finally we close it"
target.close()  
4

2 回答 2

0

target.write行的右括号位于错误的位置。尝试

target.write("%s \n %s \n %s \n" % [line1, line2, line3])
于 2012-04-28T21:58:48.890 回答
0

你的括号是错误的。你有什么:

target.write("%s \n %s \n %s \n") % [line1, line2, line3]

相当于做:

a = target.write("%s \n %s \n %s \n")
a % [line1, line2, line3]

因此,您想要的是:

target.write("%s \n %s \n %s \n" % [line1, line2, line3])
于 2012-04-28T21:59:01.613 回答