在 Ruby 中读取文件的所有常见方法是什么? [英] What are all the common ways to read a file in Ruby?
本文介绍了在 Ruby 中读取文件的所有常见方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Ruby 中读取文件的所有常用方法是什么?
What are all the common ways to read a file in Ruby?
例如,这是一种方法:
fileObj = File.new($fileName, "r")
while (line = fileObj.gets)
puts(line)
end
fileObj.close
我知道 Ruby 非常灵活.每种方法的优点/缺点是什么?
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
也可以在如上之后显式关闭文件(将块传递给 open
为您关闭它):
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屋!
查看全文