我正在学习“学习Ruby The Hard Way”,而且我一直在清理代码。当我运行ori代码时,它不会产生任何错误。当我使用更改运行我的代码时,它会运行所有内容,但也会添加错误消息。我不太清楚为什么。请帮忙。
ex17.rb:19:in `<main>': undefined method `close' for #<String:0x007febe4054c18> (NoMethodError)
ori的
from_file, to_file = ARGV
script = $0
puts "Copying from #{from_file} to #{to_file}"
#we could do these two on one line too, how?
input = File.open(from_file)
indata = input.read()
puts "The input file is #{indata.length} bytes long"
puts "Does the output file exist? #{File.exist? to_file}"
output = File.open(to_file, "w")
output.write(indata)
puts "Alright, all done."
output.close()
input.close()
我所做的更改是将输入和indata放在一起。
from_file, to_file = ARGV
script = $0
puts "Copying from #{from_file} to #{to_file}"
#we could do these two on one line too, how?
input = File.open(from_file).read()
puts "The input file is #{input.length} bytes long"
puts "Does the output file exist? #{File.exist? to_file}"
output = File.open(to_file, "w")
output.write(input)
puts "Alright, all done."
output.close()
input.close()
答案 0 :(得分:1)
在第一个代码的第input = File.open(from_file)
行中,input
的类型为File
。
但在第二个代码中,input = File.open(from_file).read()
行input
的类型为String
。并且String
没有close
方法。