簡體   English   中英

Ruby:在腳本中調用文件后如何關閉文件

[英]Ruby: How do I close a file after calling it in script

使用下面的腳本,close()語法在哪里,它將是什么?

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

一種具有兩種功能:在ensure塊中顯式調用IO#close或使用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

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

但是我建議您使用塊,這樣您的代碼會更好

像這樣

File.open(filename) do |txt|
   ...
   print txt.read
   ...
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM