通过传递output.close和input.close将2个变量更改为1

时间:2023-01-25 21:00:36

I'm going through the Learn Ruby The Hard Way and I'm stuck cleaning the code up. When I run the ori code it doesn't yield any errors. When I run my code with the change, it runs everything but also add an error message. I'm not quite sure why. Please help.

我正在学习“学习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()

The changes I made was putting the input and indata together.

我所做的改变是将输入和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()

1 个解决方案

#1


1  

in 1st code, in line input = File.open(from_file), the type of input is File.

在第一个代码中,在行input = File.open(from_file)中,输入的类型是File。

but in 2nd code, in line input = File.open(from_file).read() the type of input is String. and String has no close method.

但是在第二个代码中,在行input = File.open(from_file).read()中,输入的类型是String。和String没有close方法。

#1


1  

in 1st code, in line input = File.open(from_file), the type of input is File.

在第一个代码中,在行input = File.open(from_file)中,输入的类型是File。

but in 2nd code, in line input = File.open(from_file).read() the type of input is String. and String has no close method.

但是在第二个代码中,在行input = File.open(from_file).read()中,输入的类型是String。和String没有close方法。