所有以下API都做同样的事情:打开一个文件并为每一行调用一个块.有什么偏好我们应该使用一个而不是另一个?
File.open("file").each_line {|line| puts line}
open("file").each_line {|line| puts line}
IO.foreach("file") {|line | puts line}
Run Code Online (Sandbox Code Playgroud)
joh*_*nes 84
这三种选择之间存在重要差异.
File.open("file").each_line { |line| puts line }File.open 打开本地文件并返回文件对象IO#close给它open("file").each_line { |line| puts line }Kernel.open 查看字符串以决定如何处理它.
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/
Run Code Online (Sandbox Code Playgroud)
在第二种情况下StringIO,Kernel#open实际返回的对象包含http://google.com/的内容.如果Kernel#open返回一个File对象,它会保持打开状态,直到你调用IO#close它为止.
IO.foreach("file") { |line| puts line }IO.foreach 打开一个文件,为它读取的每一行调用给定的块,然后关闭文件.File.read("file").each { |line| puts line }你没有提到这个选择,但这是我在大多数情况下会使用的选择.
File.read 完全读取文件并将其作为字符串返回.IO.foreach此相比较清楚地表明,您正在处理文件.它在这种情况下失败:
s= File.read("/dev/zero") # => never terminates
s.each …
Run Code Online (Sandbox Code Playgroud)
ri是一个向您显示ruby文档的工具.你在shell上使用它就像这样.
ri File.open
ri open
ri IO.foreach
ri File#each_line
Run Code Online (Sandbox Code Playgroud)
有了这个,你几乎可以找到我在这里写的所有东西.
| 归档时间: |
|
| 查看次数: |
25923 次 |
| 最近记录: |