Bird
0
0

You want to process a large file line by line without loading it all into memory. Which lazy enumerator method chain is best?

hard📝 Application Q8 of 15
Ruby - Functional Patterns in Ruby
You want to process a large file line by line without loading it all into memory. Which lazy enumerator method chain is best?
AFile.open('file.txt').lazy.select { |line| line.include?('error') }
BFile.readlines('file.txt').lazy.select { |line| line.include?('error') }
CFile.read('file.txt').lazy.select { |line| line.include?('error') }
DFile.foreach('file.txt').lazy.select { |line| line.include?('error') }
Step-by-Step Solution
Solution:
  1. Step 1: Identify memory-efficient file reading

    File.foreach reads file line by line lazily, ideal for large files.
  2. Step 2: Analyze other options

    File.readlines reads entire file into memory; File.read reads whole file as string; File.open returns file object but needs iteration.
  3. Final Answer:

    File.foreach('file.txt').lazy.select { |line| line.include?('error') } -> Option D
  4. Quick Check:

    Lazy file processing = File.foreach + lazy + select [OK]
Quick Trick: Use File.foreach with lazy for memory efficiency [OK]
Common Mistakes:
  • Using File.readlines for large files
  • Using File.read which loads entire file
  • Assuming File.open is lazy by itself

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes