我正在学习“艰难地学习 Ruby”,并在尝试运行此处的示例文件时收到未定义的方法“关闭”错误: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()”似乎工作正常。作为引用,我使用了一个预先存在的输入文件,并创建了一个新的输出文件。
提前致谢。
最佳答案
由于 read()
方法调用,您的 input
不是文件对象:
input = File.open(from_file).read()
因为 read
返回 nil
或 ""
取决于 read 的长度参数,调用 input.close()
将引发 undefined method close
作为 input
在你的情况下是一个字符串和 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()
关于ruby - "Undefined method ' 关闭 '"试图关闭 Ruby 中的文件时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20764288/