在Ruby中读取文件的常见方法有哪些?

例如,这里有一个方法:

fileObj = File.new($fileName, "r")
while (line = fileObj.gets)
  puts(line)
end
fileObj.close

我知道Ruby非常灵活。每种方法的优点/缺点是什么?


当前回答

file_content = File.read('filename with extension');
puts file_content;

http://www.ruby-doc.org/core-1.9.3/IO.html#method-c-read

其他回答

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

也可以像上面那样显式地关闭文件(传递一个块来打开并为你关闭它):

f = File.open("my/file/path", "r")
f.each_line do |line|
  puts line
end
f.close

如果文件不是太长,最简单的方法是:

puts File.read(file_name)

事实上,IO。读取或文件。读取后自动关闭文件,因此不需要使用file。用木块打开。

file_content = File.read('filename with extension');
puts file_content;

http://www.ruby-doc.org/core-1.9.3/IO.html#method-c-read

content = `cat file`

我认为这种方法是最“不寻常”的一种。也许这有点棘手,但如果安装了cat,它就可以工作。

返回your_file.log或.txt中的最后n行

path = File.join(Rails.root, 'your_folder','your_file.log')

last_100_lines = `tail -n 100 #{path}`