Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
未定义的方法';关闭';用于Ruby中的main:Object(nomethoderor)_Ruby_File_Fclose_Learn Ruby The Hard Way - Fatal编程技术网

未定义的方法';关闭';用于Ruby中的main:Object(nomethoderor)

未定义的方法';关闭';用于Ruby中的main:Object(nomethoderor),ruby,file,fclose,learn-ruby-the-hard-way,Ruby,File,Fclose,Learn Ruby The Hard Way,程序一直正常运行到最后,但在打印第二个文件的内容后,立即出现标题错误消息,导致程序崩溃 我使用(.class)再次检查了txt、txt\u,并确认它们都是文件对象。为什么关闭不起作用?您需要对文件对象调用close: filename = ARGV.first txt = open filename puts "Here's your file #{filename}:" print txt.read puts "Type the filename again: " file_again

程序一直正常运行到最后,但在打印第二个文件的内容后,立即出现标题错误消息,导致程序崩溃


我使用(.class)再次检查了txt、txt\u,并确认它们都是文件对象。为什么关闭不起作用?

您需要对文件对象调用
close

filename = ARGV.first

txt = open filename

puts "Here's your file #{filename}:"
print txt.read

puts "Type the filename again: "
file_again = $stdin.gets.chomp

txt_again = open file_again

print txt_again.read

close(txt)
close(txt_again)

您需要对文件对象调用
close

filename = ARGV.first

txt = open filename

puts "Here's your file #{filename}:"
print txt.read

puts "Type the filename again: "
file_again = $stdin.gets.chomp

txt_again = open file_again

print txt_again.read

close(txt)
close(txt_again)

虽然答案在技术上符合您的用法
File.read(txt)
File.open(txt,&:read)
都是自动关闭的。这意味着您可以打开并读取该文件,而无需确保随后将其关闭。@engineersmnky我从未见过这种语法
file.open(txt,&:read)
:D@engineersmnky根据这一点,只有File.open(txt,&:read)是自动关闭的,File.read(txt)不是。必须向open方法传递一个块,使其成为self-closing@Coolshanth根据官方文件上的。打开文件,可以选择查找给定的偏移量,然后返回长度字节(默认为文件的其余部分)。读取确保文件在返回之前关闭。虽然答案在技术上符合您的用法
file.read(txt)
file.open(txt,&:read)
都是自动关闭的。这意味着您可以打开并读取该文件,而无需确保随后将其关闭。@engineersmnky我从未见过这种语法
file.open(txt,&:read)
:D@engineersmnky根据这一点,只有File.open(txt,&:read)是自动关闭的,File.read(txt)不是。必须向open方法传递一个块,使其成为self-closing@Coolshanth根据官方文件上的。打开文件,可以选择查找给定的偏移量,然后返回长度字节(默认为文件的其余部分)。读取确保文件在返回前关闭。。