Ruby中的File.open,open和IO.foreach有什么区别? [英] File.open, open and IO.foreach in Ruby, what is the difference?

查看:72
本文介绍了Ruby中的File.open,open和IO.foreach有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下所有API都具有相同的作用:打开文件并为每一行调用一个块.我们应该优先使用一个优先选项吗?

All of the following API do the same thing: open a file and call a block for each line. Is there any preference we should use one than another?

File.open("file").each_line {|line| puts line}
open("file").each_line {|line| puts line}   
IO.foreach("file") {|line | puts line}

推荐答案

这三种选择之间存在重要区别.

There are important differences beetween those 3 choices.

  • File.open打开本地文件并返回文件对象
  • 文件保持打开状态,直到您在其上调用IO#close
  • File.open opens a local file and returns a file object
  • the file stays open until you call IO#close on it

Kernel.open查看字符串以确定如何处理它.

Kernel.open looks at the string to decide what to do with it.

open(".irbrc").class # => File
open("http://google.com/").class # => StringIO
File.open("http://google.com/") # => Errno::ENOENT: No such file or directory - http://google.com/

在第二种情况下,由Kernel#open返回的StringIO对象实际上保存了 http://google.com/的内容.如果Kernel#open返回一个File对象,则该对象将保持打开状态,直到您在其上调用IO#close.

In the second case the StringIO object returned by Kernel#open actually holds the content of http://google.com/. If Kernel#open returns a File object, it stays open untill you call IO#close on it.

  • IO.foreach打开文件,为其读取的每一行调用给定的块,然后关闭文件.
  • 您不必担心会关闭文件.
  • IO.foreach opens a file, calls the given block for each line it reads, and closes the file afterwards.
  • You don't have to worry about closing the file.

您没有提到这一选择,但这是我在大多数情况下都会使用的选择.

You didn't mention this choice, but this is the one I would use in most cases.

  • File.read完全读取文件并将其作为字符串返回.
  • 您不必担心会关闭文件.
  • IO.foreach相比,这很清楚,您正在处理文件.
  • 为此的内存复杂度为O(n).如果您知道要处理的是小文件,这不是缺点.但是,如果它可以是一个大文件,并且您知道自己的内存复杂度可以小于O(n),则不要使用此选择.
  • File.read reads a file completely and returns it as a string.
  • You don't have to worry about closing the file.
  • In comparison to IO.foreach this makes it clear, that you are dealing with a file.
  • The memory complexity for this is O(n). If you know you are dealing with a small file, this is no drawback. But if it can be a big file and you know your memory complexity can be smaller than O(n), don't use this choice.

在这种情况下失败:

 s= File.read("/dev/zero") # => never terminates
 s.each …

ri

ri是一个向您显示ruby文档的工具.您可以在外壳上像这样使用它.

ri

ri is a tool which shows you the ruby documentation. You use it like this on your shell.

ri File.open
ri open
ri IO.foreach
ri File#each_line

有了这个,您几乎可以找到我在这里写的所有内容.

With this you can find almost everything I wrote here and much more.

这篇关于Ruby中的File.open,open和IO.foreach有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆