简体   繁体   中英

Comparison in reading lines from file

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 (ie, close the file successfully afterwards)?
  2. Is there a scenario in which one method surpasses the others (ie, the given file is relatively large)? If so, what's the best practice?

您显示的第一种方式即使在发生错误时也将关闭文件,而其他两种则不会。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM