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.