ruby - "Undefined method ' 关闭 '"试图关闭 Ruby 中的文件时

标签 ruby fclose learn-ruby-the-hard-way

我正在学习“艰难地学习 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/

相关文章:

ruby - 如何减少 Ruby 的 if 条件?

android - fclose 在 android 和 linux 上的工作方式不同

c - fclose 是否立即释放文件?

ruby - 要求命令在 Snow Leopard 上的 bash irb 中不起作用

ruby - 有电子邮件 Hook 之类的东西吗?

ruby-on-rails - 为 memcached 和 Rails 组合片段和对象缓存的最佳方法

ruby-on-rails - 为什么我无法使用 "rake db:create"创建数据库?

C - 使用 fopen、fclose、fputc 等

ruby - 正确的 Assert_Raise 单元测试和异常类的使用

ruby - gets.chomp 在 ruby​​ 中的一个函数中