"Undefined method 'close'" when trying to close a file in Ruby

4.6k Views Asked by At

I'm working through "Learn Ruby the Hard Way" and receive an undefined method 'close' error when trying to run the example file here: http://ruby.learncodethehardway.org/book/ex17.html

My code, specifically is:

from_file, to_file = ARGV
script = $0

puts "Copying from #{from_file} to #{to_file}."

input = File.open(from_file).read()
puts "The input file is #{input.length} bytes long."

puts "Does the output file exist? #{File.exists? to_file}"
puts "Ready, hit RETURN to contine, CTRL-C to abort."
STDIN.gets

output = File.open(to_file, 'w')
output.write(input)

puts "Alright, all done."

output.close()
input.close()

The error I receive is only for the last line 'input.close()', as 'output.close()' seems to work fine. For reference, I'm using a preexisting input file, and creating a new output file.

Thanks in advance.

1

There are 1 best solutions below

8
On BEST ANSWER

Your input is not a file object because of the read() method call:

input = File.open(from_file).read()

Since read returns either nil or "" depending upon the length parameter to read, calling input.close() will raise undefined method close as input in your case is a string and String does not have close() method.

So instead of calling File.open(from_file).read() and calling the close() method, you can just call the File.read():

from_file, to_file = ARGV
script = $0

puts "Copying from #{from_file} to #{to_file}."

input = File.read(from_file)
puts "The input file is #{input.length} bytes long."

puts "Does the output file exist? #{File.exists? to_file}"
puts "Ready, hit RETURN to contine, CTRL-C to abort."
STDIN.gets

output = File.open(to_file, 'w')
output.write(input)

puts "Alright, all done."

output.close()