0
0
Rubyprogramming~20 mins

Why file handling matters in Ruby - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Handling Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code that writes and reads a file?

Consider this Ruby code that writes a string to a file and then reads it back. What will it print?

Ruby
File.open('test.txt', 'w') do |file|
  file.puts 'Hello, file handling!'
end

content = File.read('test.txt')
puts content.strip
AError: No such file or directory
BHello, file handling!
Ctest.txt
Dnil
Attempts:
2 left
💡 Hint

Think about what file.puts does and how File.read works.

🧠 Conceptual
intermediate
1:30remaining
Why is it important to close files after opening them in Ruby?

Why should you always close a file after opening it in Ruby?

ATo speed up the computer's processor
BTo make the file invisible on the disk
CTo delete the file automatically
DTo free system resources and avoid file corruption
Attempts:
2 left
💡 Hint

Think about what happens if too many files stay open.

🔧 Debug
advanced
2:00remaining
What error does this Ruby code raise when trying to read a non-existent file?

Look at this Ruby code trying to read a file that does not exist. What error will it raise?

Ruby
content = File.read('missing_file.txt')
puts content
AErrno::ENOENT (No such file or directory @ rb_sysopen - missing_file.txt)
BNoMethodError: undefined method 'read' for File
CSyntaxError: unexpected end-of-input
DTypeError: no implicit conversion of nil into String
Attempts:
2 left
💡 Hint

What happens when Ruby tries to open a file that isn't there?

📝 Syntax
advanced
2:00remaining
Which Ruby code snippet correctly appends text to an existing file?

Choose the Ruby code that correctly adds the line 'Appended line' to the end of 'log.txt'.

AFile.open('log.txt', 'w') { |file| file.puts 'Appended line' }
BFile.read('log.txt') << 'Appended line'
CFile.open('log.txt', 'a') { |file| file.puts 'Appended line' }
DFile.write('log.txt', 'Appended line')
Attempts:
2 left
💡 Hint

Remember, 'a' mode means append, 'w' means overwrite.

🚀 Application
expert
3:00remaining
How many lines will the file contain after running this Ruby code?

This Ruby code writes three lines to a file, then reads and appends one more line. How many lines will the file have at the end?

Ruby
File.open('data.txt', 'w') do |file|
  file.puts 'Line 1'
  file.puts 'Line 2'
  file.puts 'Line 3'
end

lines = File.readlines('data.txt')
File.open('data.txt', 'a') { |file| file.puts "Line #{lines.size + 1}" }
A4
B3
C1
D5
Attempts:
2 left
💡 Hint

Count the lines written first, then the appended line.