2
這是我正在運行的代碼,直到第15行才能正常運行。我運行的命令是:ruby ex16.rb text.txt
。這是一個實踐樣本我寫這意味着是一個簡單的小的文本編輯器:未定義的方法大小爲#<File:text.txt>(NoMethodError)
filename = ARGV.first
script = $0
puts "We're going to erase #{filename}."
puts "if you don't want that, hit CTRL-C (^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. Goodbye!"
target.truncate(target.size)
puts "Now I'm 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()undefined method 'size'
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 "And finally, we close it."
target.close()
您使用的是什麼版本的Ruby,以及在什麼平臺上?如果你想擦除文件內容,爲什麼不只是做target.truncate(0)? –
在1.8.6中出現同樣錯誤,在1.9.2中工作。奇怪,因爲鎬1.8對File.size沒有特別的說明。 – BernardK
迭戈 - 這是一個練習練習,我被要求寫。 – matthewp