在Ruby中读取文件的常见方法有哪些?
例如,这里有一个方法:
fileObj = File.new($fileName, "r")
while (line = fileObj.gets)
puts(line)
end
fileObj.close
我知道Ruby非常灵活。每种方法的优点/缺点是什么?
在Ruby中读取文件的常见方法有哪些?
例如,这里有一个方法:
fileObj = File.new($fileName, "r")
while (line = fileObj.gets)
puts(line)
end
fileObj.close
我知道Ruby非常灵活。每种方法的优点/缺点是什么?
当前回答
我通常这样做:
open(path_in_string, &:read)
这将为您提供整个文本作为字符串对象。它只能在Ruby 1.9下工作。
其他回答
我通常这样做:
open(path_in_string, &:read)
这将为您提供整个文本作为字符串对象。它只能在Ruby 1.9下工作。
返回your_file.log或.txt中的最后n行
path = File.join(Rails.root, 'your_folder','your_file.log')
last_100_lines = `tail -n 100 #{path}`
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
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,它就可以工作。