Consider this Ruby code that writes a string to a file and then reads it back. What will it print?
File.open('test.txt', 'w') do |file| file.puts 'Hello, file handling!' end content = File.read('test.txt') puts content.strip
Think about what file.puts does and how File.read works.
The code writes the string 'Hello, file handling!' to 'test.txt' and then reads it back. The puts prints the content without extra spaces.
Why should you always close a file after opening it in Ruby?
Think about what happens if too many files stay open.
Closing files frees system resources and ensures data is saved properly. Leaving files open can cause errors or data loss.
Look at this Ruby code trying to read a file that does not exist. What error will it raise?
content = File.read('missing_file.txt') puts content
What happens when Ruby tries to open a file that isn't there?
Ruby raises an Errno::ENOENT error when a file does not exist and you try to read it.
Choose the Ruby code that correctly adds the line 'Appended line' to the end of 'log.txt'.
Remember, 'a' mode means append, 'w' means overwrite.
Opening a file with mode 'a' appends text. Mode 'w' overwrites the file. Using File.read returns a string but does not write back. File.write overwrites the file.
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?
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}" }
Count the lines written first, then the appended line.
The code writes 3 lines, reads them (3 lines), then appends a 4th line labeled 'Line 4'. So the file ends with 4 lines.