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