這裏是我的代碼:讀取文件(紅寶石堅硬方式EX16)
filename = ARGV.first
puts "We're gong to erase #{filename}"
puts "If you don't want that, hit CTRL-C (^C)."
puts "If you do want that, hit RETURN."
$stdin.gets
puts "Opening the file..."
target = open(filename, 'w')
puts "Truncating the file. Goodbye!"
target.truncate(0)
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
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")
print target.read
puts "And finally, we close it."
target.close
我試圖把它寫,然後閱讀。如果我在腳本的底部再次執行target.close
,然後再執行target = open(filename)
,它將起作用。有另一種方法嗎?
我看到this關於python的文章解釋你需要在寫入文件後關閉文件。這同樣適用於Ruby嗎?我需要使用同花順嗎?
另外我應該閱讀和關閉後使用括號?這個例子沒有。
這不是一個語言問題,更是一個文件系統/操作系統問題。你在做什麼操作系統? Windows具有強制鎖定,這意味着如果您打開了文件,則在關閉文件之前無法再打開它。 Unix(包括Mac)將允許您隨意地在文件上塗寫文件。 – Schwern
這個「Ruby hard way」代碼看起來不像Ruby,它看起來像是從Python逐行直譯的代碼。 – steenslag
「Learn Ruby The Hard Way」似乎是[「Learn Python The Hard Way」](http://learnpythonthehardway.org/book/ex16.html)的直接翻譯。 @steenslag是對的,這不是很好的Ruby。我會避免它。我建議使用Learn Python The Hard Way來學習編程技術(文件操作技術是普遍的),並使用其他方法學習Ruby,如[原始Pickaxe](http://ruby-doc.com/docs/ProgrammingRuby/) 。我不*推薦[更新的Ruby編程Ruby 2.0](http://www.amazon.com/gp/review/RBK4K4T9YDA9L/ref=cm_cr_pr_rvw_ttl?ie=UTF8&ASIN=1937785491)。 – Schwern