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 }
- Do those three methods correctly handle the file (i.e., close the file successfully afterwards)?
- 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?