Paul Thompson Paul Thompson - 2 months ago 10
Ruby Question

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

Using the below script, where would the close() syntax go and what would it be?

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

Answer

One has two abilities: explicitly call IO#close within ensure block or use a block version of 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