“尝试在Ruby中关闭文件时,未定义的方法'关闭'”

时间:2013-12-24 16:56:16

标签: ruby fclose learn-ruby-the-hard-way

我正在尝试“学习Ruby the Hard Way”并在尝试运行示例文件时收到未定义的方法“关闭”错误:http://ruby.learncodethehardway.org/book/ex17.html

我的代码,具体是:

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()

我收到的错误仅适用于最后一行'input.close()',因为'output.close()'似乎工作正常。作为参考,我正在使用预先存在的输入文件,并创建一个新的输出文件。

提前致谢。

1 个答案:

答案 0 :(得分:5)

由于input方法调用,您的read()不是文件对象:

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

由于read会根据read的长度参数返回nil"",因此调用input.close()会将undefined method close提升为input 1}}在您的情况下是一个字符串,而String没有close()方法。

因此,您无需致电File.open(from_file).read()并调用close()方法,而只需致电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()