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.
Your
input
is not a file object because of theread()
method call:Since
read
returns eithernil
or""
depending upon the length parameter to read, callinginput.close()
will raiseundefined method close
asinput
in your case is a string andString
does not haveclose()
method.So instead of calling
File.open(from_file).read()
and calling theclose()
method, you can just call theFile.read()
: