[英]How do I redirect stderr and stdout to file for a Ruby script?
[英]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.