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:
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")
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.
johannes Nov 13 '09 at 12:30 2009-11-13 12:30
source share