0

我正在经历Learn Ruby The Hard Way,我一直在清理代码。当我运行 ori 代码时,它不会产生任何错误。当我使用更改运行我的代码时,它会运行所有内容,但还会添加一条错误消息。我不太清楚为什么。请帮忙。

ex17.rb:19:in `<main>': undefined method `close' for #<String:0x007febe4054c18> (NoMethodError)

原产地

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

我所做的更改是将输入和数据放在一起。

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

1 回答 1

1

在第一个代码中,在 lineinput = File.open(from_file)中,类型inputFile

但在第二个代码中,input = File.open(from_file).read()类型inputString. 并且String没有close方法。

于 2013-10-17T15:45:59.583 回答