Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - File IO
What will be the output of this Ruby code?
File.open('sample.txt', 'w') do |f|
  f.puts 'Line 1'
  f.puts 'Line 2'
end
puts File.read('sample.txt')
ALine 1 Line 2
BLine 1 Line 2
CError: file not found
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Write lines to file inside block

    The block writes two lines: 'Line 1' and 'Line 2' to 'sample.txt'.
  2. Step 2: Read and print file content

    After the block, File.read reads the file content, which includes both lines separated by newlines.
  3. Final Answer:

    Line 1 Line 2 -> Option A
  4. Quick Check:

    File.open block writes lines; File.read outputs lines with newlines = B [OK]
Quick Trick: File.open with block writes; File.read reads full content [OK]
Common Mistakes:
  • Expecting lines without newline characters
  • Confusing output format with spaces instead of newlines
  • Assuming file is empty or missing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes