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

Kyl*_*dha 1 ruby fclose learn-ruby-the-hard-way

我正在尝试"学习Ruby the Hard Way"并在尝试运行示例文件时收到未定义的方法'close'错误: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()
Run Code Online (Sandbox Code Playgroud)

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

提前致谢.

vee*_*vee 5

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

input = File.open(from_file).read()
Run Code Online (Sandbox Code Playgroud)

因为read返回nil或者""根据要读取的长度参数返回,所以调用input.close()undefined method closeinput你的情况一样提高字符串并且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()
Run Code Online (Sandbox Code Playgroud)

  • @bjhaid,请帮助我理解`没有关联的块,File.open是从您发布的链接中取得的:: new`的同义词. (2认同)