Paul Thompson
Paul Thompson

Reputation: 27

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

Upvotes: 0

Views: 33

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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

Upvotes: 1

Sergio Rivas
Sergio Rivas

Reputation: 563

You can use the close method, in your context: txt.close

But I recommend you to use blocks, so your code will be better

Something like this

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

Upvotes: 0

Related Questions