0
0
Rubyprogramming~5 mins

File.readlines for line-by-line in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does File.readlines do in Ruby?

File.readlines reads a file and returns an array where each element is a line from the file.

Click to reveal answer
beginner
How can you read a file line-by-line using File.readlines?

Use File.readlines('filename').each do |line| ... end to process each line one by one.

Click to reveal answer
beginner
What type of object does File.readlines return?

It returns an array of strings, where each string is a line from the file including the newline character.

Click to reveal answer
intermediate
How do you remove the newline character from each line read by File.readlines?

You can use line.chomp inside the loop to remove the newline character from each line.

Click to reveal answer
intermediate
Why might you prefer File.readlines over File.read when processing files?

File.readlines breaks the file into lines automatically, making it easier to process line-by-line without manual splitting.

Click to reveal answer
What does File.readlines('file.txt') return?
AAn integer count of lines
BA single string with the whole file content
CA file object
DAn array of lines from the file
How do you iterate over each line after using File.readlines?
AUsing <code>.each do |line| ... end</code>
BUsing <code>.split</code>
CUsing <code>.readline</code>
DUsing <code>.open</code>
Which method removes the newline character from a string in Ruby?
A<code>strip</code>
B<code>chomp</code>
C<code>delete</code>
D<code>split</code>
If you want to read a file line-by-line without loading all lines at once, which method is better than File.readlines?
A<code>File.read</code>
B<code>File.write</code>
C<code>File.foreach</code>
D<code>File.open</code>
What will File.readlines('file.txt')[0] return?
AThe first line of the file as a string
BThe first character of the file
CThe number of lines in the file
DAn error
Explain how to use File.readlines to read a file and print each line without the newline character.
Think about reading lines into an array and looping through it.
You got /4 concepts.
    Describe the difference between File.readlines and File.foreach when reading files line-by-line.
    Consider memory usage and when lines are loaded.
    You got /4 concepts.