2016-09-17 77 views
0

使用下面的腳本,close()語法的位置在哪裏,它會是什麼?Ruby:如何在腳本中調用文件後關閉文件

print "Enter the filename you want to open here > " 
filename = $stdin.gets.chomp 
txt = open(filename) 

puts "Here's your file #{filename}" 
print txt.read 
print "Type the filename again: " 

file_again = $stdin.gets.chomp 
txt_again = open(file_again) 

print txt_again.read 

回答

1

一個具有兩種能力:顯式調用IO#closeensure塊內或使用IO#read/open塊版本:

filename = $stdin.gets.chomp 
begin 
    txt = open(filename) 
    puts "Here's your file #{filename}" 
    print txt.read 
ensure 
    txt.close 
end 


filename = $stdin.gets.chomp 
open(filename) do |txt| 
    puts "Here's your file #{filename}" 
    print txt.read 
end 
0

可以使用close方法,在您的上下文:txt.close

但我建議你使用塊,所以你的代碼會更好

像這樣的事情

File.open(filename) do |txt| 
    ... 
    print txt.read 
    ... 
end 
相關問題