0

There are multiple ways to read lines from a file. Here are three:

# 1
File.open("temp.txt", "r") do |f|
  f.each_line { |l| puts l }
end

# 2
File.open("temp.txt", "r").each_line { |l| puts l }.close

# 3
File.readlines("temp.txt").each { |l| puts l }
  1. Do those three methods correctly handle the file (i.e., close the file successfully afterwards)?
  2. Is there a scenario in which one method surpasses the others (i.e., the given file is relatively large)? If so, what's the best practice?
sbs
  • 4,102
  • 5
  • 40
  • 54
  • You can answer this for yourself by reading the documentation and http://stackoverflow.com/questions/25189262/why-is-slurping-a-file-bad. – the Tin Man Aug 24 '15 at 02:51

1 Answers1

0

The first way you show would take care of closing the file even when an error occurs, while the other two would not.

satoru
  • 31,822
  • 31
  • 91
  • 141
  • For the method 3, it doesn't need to close the file since `File.readlines("temp.txt")` returns an `Array`, right? – sbs Aug 24 '15 at 00:39
  • @JohnnySun This would read the whole files into memory, so you won't want to do this if you are processing a large file. – satoru Aug 24 '15 at 00:44
  • @JohnnySun `File.readlines` also handles file opening/closing. It even does not return file object you may close yourself. – joanbm Aug 24 '15 at 00:46