Ruby:如何在脚本中调用文件后关闭文件

时间:2016-09-17 04:31:34

标签: ruby

使用下面的脚本,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

2 个答案:

答案 0 :(得分:1)

一个人有两种能力:在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

答案 1 :(得分:0)

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

但我建议你使用块,这样你的代码会更好

像这样的东西

File.open(filename) do |txt|
   ...
   print txt.read
   ...
end
相关问题