File.open, open and IO.foreach in Ruby, what's the difference?

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

File.open("file").each_line {|line| puts line} open("file").each_line {|line| puts line} IO.foreach("file") {|line | puts line} 
+46
ruby file-io
Nov 13 '09 at 5:00
source share
1 answer

There are important differences between these three choices.

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

  • File.open opens a local file and returns a file object
  • the file remains open until you call IO#close on it

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

Kernel.open looks at the line 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/ 

In the second case, the StringIO object returned by Kernel#open actually contains the contents of http://google.com/ . If Kernel#open returns a File object, it remains open until you name IO#close on it.

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

  • IO.foreach opens the file, calls the given block for each line it reads, and closes the file afterwards.
  • You do not need to worry about closing the file.

File.read("file").each { |line| puts line }

You did not mention this choice, but it is one that I would use in most cases.

  • File.read reads the file completely and returns it as a string.
  • You do not need to worry about closing the file.
  • Compared 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 that you are dealing with a small file, this is not a disadvantage. But if it can be a large file, and you know that your memory complexity may be less than O (n), do not use this choice.

In this situation, it fails:

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

P

ri is a tool that shows you ruby ​​documentation. You use it the same way as 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.

+73
Nov 13 '09 at 12:30
source share
β€” -



All Articles