在Ruby中读取文件的常用方法是什么? [英] What are all the common ways to read a file in Ruby?
本文介绍了在Ruby中读取文件的常用方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,下面是一个方法:
fileObj = File.new($ fileName,r)
while(line = fileObj.gets)
puts(line)
end
fileObj.close
我知道Ruby非常灵活。什么是每种方法的好处/缺点?
解决方案
File.open(my / file / path,r)do | f |
f.each_line do | line |
puts line
end
end
#文件在块结尾自动关闭
也可以像上面那样明确地关闭文件(将块传给打开
为你关闭):
f = File.open(my / file / path,r)
f.each_line do | line |
puts line
end
f.close
What are all the common ways to read a file in Ruby?
For instance, here is one method:
fileObj = File.new($fileName, "r")
while (line = fileObj.gets)
puts(line)
end
fileObj.close
I know Ruby is extremely flexible. What are the benefits/drawbacks of each approach?
解决方案
File.open("my/file/path", "r") do |f|
f.each_line do |line|
puts line
end
end
# File is closed automatically at end of block
It is also possible to explicitly close file after as above (pass a block to open
closes it for you):
f = File.open("my/file/path", "r")
f.each_line do |line|
puts line
end
f.close
这篇关于在Ruby中读取文件的常用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文