Concept Flow - File.readlines for line-by-line
Open file
Read all lines into array
Iterate over array
Process each line
Close file
The program opens a file, reads all lines into an array, then processes each line one by one.
lines = File.readlines('example.txt') lines.each do |line| puts line.chomp end
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Call File.readlines('example.txt') | Reads entire file | Array of lines: ["Hello\n", "World\n", "Ruby\n"] |
| 2 | Start iteration over array | First element: "Hello\n" | line = "Hello\n" |
| 3 | Print line.chomp | Remove trailing newline | Output: Hello |
| 4 | Next iteration | Second element: "World\n" | line = "World\n" |
| 5 | Print line.chomp | Remove trailing newline | Output: World |
| 6 | Next iteration | Third element: "Ruby\n" | line = "Ruby\n" |
| 7 | Print line.chomp | Remove trailing newline | Output: Ruby |
| 8 | End iteration | No more elements | Iteration stops |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| lines | nil | ["Hello\n", "World\n", "Ruby\n"] | ["Hello\n", "World\n", "Ruby\n"] | ["Hello\n", "World\n", "Ruby\n"] | ["Hello\n", "World\n", "Ruby\n"] |
| line | nil | "Hello\n" | "World\n" | "Ruby\n" | nil |
File.readlines('filename') reads all lines into an array.
Each element includes the newline character '\n'.
Use .each to loop line-by-line.
Use line.chomp to remove trailing newline when printing.
File is closed after reading all lines.File.readlines('example.txt') return in Ruby?File.readlines reads the whole file and returns an array of lines.chomp.data.txt into an array in Ruby?File.readlines (no underscore or plural misspelling).notes.txt with these lines:Line 1 Line 2 Line 3
lines = File.readlines('notes.txt')
puts lines[1]lines[1] is "Line 2\n".lines = File.readlines('file.txt')
lines.each do |line|
puts line.chomp
endfile.txt exists and is readable.File.readlines reads all lines into an array, each ending with a newline.each to iterate and chomp removes trailing newline before printing.data.txt and create a new array containing only lines that include the word "error" (case insensitive). Which Ruby code correctly does this using File.readlines?select to keep lines where line.downcase.include?('error') is true.map which returns booleans, not lines. File.readlines('data.txt').filter { |line| line.include?('Error') } checks case-sensitive 'Error'. File.readlines('data.txt').reject { |line| line.downcase.include?('error') } rejects lines with 'error', opposite of requirement.Pass the test and this pattern moves unknown