0
0
Rubyprogramming~10 mins

File.readlines for line-by-line in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to read all lines from a file named 'data.txt' into an array.

Ruby
lines = File.[1]('data.txt')
Drag options to blanks, or click blank then click option'
Agets
Bread
Copen
Dreadlines
Attempts:
3 left
💡 Hint
Common Mistakes
Using File.read returns the whole file as a single string, not an array of lines.
Using File.open returns a file object, not the lines directly.
2fill in blank
medium

Complete the code to print each line from the file 'notes.txt' using File.readlines.

Ruby
File.[1]('notes.txt').each do |line|
  puts line
end
Drag options to blanks, or click blank then click option'
Areadlines
Bforeach
Copen
Dread
Attempts:
3 left
💡 Hint
Common Mistakes
Using File.read returns a string, which does not have an each method for lines.
Using File.foreach reads lines one by one but is not called on File.readlines.
3fill in blank
hard

Fix the error in the code to correctly read lines from 'log.txt' and print them.

Ruby
lines = File.[1]('log.txt')
lines.each do |line|
  puts line
end
Drag options to blanks, or click blank then click option'
Aread
Breadlines
Copen
Dgets
Attempts:
3 left
💡 Hint
Common Mistakes
Using File.read returns a string, which cannot be iterated line by line with each.
Using File.open returns a file object, not an array of lines.
4fill in blank
hard

Fill both blanks to create a hash with line numbers as keys and lines as values from 'input.txt'.

Ruby
lines = File.[1]('input.txt')
line_hash = lines.each_with_index.to_h { |[2], i| [i + 1, [2]] }
Drag options to blanks, or click blank then click option'
Areadlines
Bline
Dread
Attempts:
3 left
💡 Hint
Common Mistakes
Using File.read instead of File.readlines returns a string, which does not work with each_with_index as expected.
Using a wrong variable name in the block causes errors.
5fill in blank
hard

Fill all three blanks to create a hash with uppercase line keys and their lengths as values from 'file.txt'.

Ruby
lines = File.[1]('file.txt')
result = lines.to_h { |[2]| [[2].upcase, [3] ] }
Drag options to blanks, or click blank then click option'
Aread
Breadlines
Cline.length
Dline
Attempts:
3 left
💡 Hint
Common Mistakes
Using File.read returns a string, which cannot be iterated like an array.
Mixing variable names or forgetting to call upcase causes errors.