What are all the common ways to read a file in Rub

2019-01-03 11:34发布

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?

标签: ruby file-io
10条回答
淡お忘
2楼-- · 2019-01-03 11:54

return last n lines from your_file.log or .txt

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

last_100_lines = `tail -n 100 #{path}`
查看更多
我命由我不由天
3楼-- · 2019-01-03 11:58

The easiest way if the file isn't too long is:

puts File.read(file_name)

Indeed, IO.read or File.read automatically close the file, so there is no need to use File.open with a block.

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-03 11:58

You can read the file all at once:

content = File.readlines 'file.txt'
content.each_with_index{|line, i| puts "#{i+1}: #{line}"}

When the file is large, or may be large, it is usually better to process it line-by-line:

File.foreach( 'file.txt' ) do |line|
  puts line
end

Sometimes you want access to the file handle though or control the reads yourself:

File.open( 'file.txt' ) do |f|
  loop do
    break if not line = f.gets
    puts "#{f.lineno}: #{line}"
  end
end

In case of binary files, you may specify a nil-separator and a block size, like so:

File.open('file.bin', 'rb') do |f|
  loop do
    break if not buf = f.gets(nil, 80)
    puts buf.unpack('H*')
  end
end

Finally you can do it without a block, for example when processing multiple files simultaneously. In that case the file must be explicitly closed (improved as per comment of @antinome):

begin
  f = File.open 'file.txt'
  while line = f.gets
    puts line
  end
ensure
  f.close
end

References: File API and the IO API.

查看更多
姐就是有狂的资本
5楼-- · 2019-01-03 12:01
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
查看更多
We Are One
6楼-- · 2019-01-03 12:02
file_content = File.read('filename with extension');
puts file_content;

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

查看更多
走好不送
7楼-- · 2019-01-03 12:03
content = `cat file`

I think this method is the most "uncommon" one. Maybe it is kind of tricky, but it works if cat is installed.

查看更多
登录 后发表回答