0
0
Rubyprogramming~20 mins

IO modes (r, w, a) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby IO Master
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 using mode 'r'?
Consider this Ruby code that tries to read a file in 'r' mode. What will it output if the file 'example.txt' contains the text 'Hello World'?
Ruby
File.open('example.txt', 'r') do |file|
  puts file.read
end
AHello World
BFile not found error
CEmpty output
DPermission denied error
Attempts:
2 left
💡 Hint
Mode 'r' opens the file for reading only.
Predict Output
intermediate
2:00remaining
What happens when opening a file with mode 'w'?
Given this Ruby code, what will be the content of 'output.txt' after running it?
Ruby
File.open('output.txt', 'w') do |file|
  file.write('First line')
end
File.open('output.txt', 'w') do |file|
  file.write('Second line')
end
AThe file contains 'First line'
BThe file contains 'First lineSecond line'
CThe file is empty
DThe file contains 'Second line'
Attempts:
2 left
💡 Hint
Mode 'w' overwrites the file each time it opens it.
Predict Output
advanced
2:00remaining
What is the output after appending text with mode 'a'?
Assuming 'log.txt' initially contains 'Start\n', what will be the content after running this Ruby code?
Ruby
File.open('log.txt', 'a') do |file|
  file.puts('Entry 1')
end
File.open('log.txt', 'a') do |file|
  file.puts('Entry 2')
end
content = File.read('log.txt')
puts content
A
Start
B
Entry 1
Entry 2
C
Start
Entry 1
Entry 2
D
Start
Entry 2
Attempts:
2 left
💡 Hint
Mode 'a' adds new content to the end without deleting existing content.
Predict Output
advanced
2:00remaining
What error occurs when opening a non-existent file in 'r' mode?
What happens when this Ruby code runs and 'missing.txt' does not exist?
Ruby
File.open('missing.txt', 'r') do |file|
  puts file.read
end
AErrno::ENOENT (No such file or directory) error
BEmpty output
CPermission denied error
DCreates an empty file named 'missing.txt'
Attempts:
2 left
💡 Hint
Mode 'r' requires the file to exist.
🧠 Conceptual
expert
2:00remaining
How do 'w' and 'a' modes differ when writing to a file?
Which statement correctly describes the difference between opening a file in 'w' mode versus 'a' mode in Ruby?
A'w' mode appends to the file, 'a' mode overwrites the file content
B'w' mode overwrites the file content, 'a' mode appends to the file without deleting existing content
C'w' mode only writes if the file exists, 'a' mode creates a new file if it does not exist
D'w' mode opens the file for reading and writing, 'a' mode opens the file for reading only
Attempts:
2 left
💡 Hint
Think about what happens to existing content in each mode.