0
0
Rubyprogramming~20 mins

File.write for writing in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Write 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 File.write?

Consider this Ruby code that writes to a file and then reads it back:

File.write('test.txt', 'Hello')
content = File.read('test.txt')
puts content

What will be printed?

Ruby
File.write('test.txt', 'Hello')
content = File.read('test.txt')
puts content
Atest.txt
Bnil
CHello
DError: file not found
Attempts:
2 left
💡 Hint

File.write writes the string to the file, and File.read reads it back.

Predict Output
intermediate
2:00remaining
What does File.write return in Ruby?

Look at this Ruby code:

result = File.write('output.txt', 'Data')

What is the value of result after this runs?

Ruby
result = File.write('output.txt', 'Data')
AThe number of bytes written (4)
BThe string 'Data'
Ctrue
Dnil
Attempts:
2 left
💡 Hint

File.write returns how many bytes it wrote to the file.

🔧 Debug
advanced
2:00remaining
Why does this File.write code raise an error?

What error does this Ruby code raise?

File.write(123, 'Hello')
Ruby
File.write(123, 'Hello')
AArgumentError: wrong number of arguments
BTypeError: no implicit conversion of Integer into String
CErrno::ENOENT: No such file or directory
DNo error, writes file named '123'
Attempts:
2 left
💡 Hint

File.write expects a string filename, not a number.

📝 Syntax
advanced
2:00remaining
Which option correctly appends text to a file using File.write?

You want to add text to the end of an existing file. Which Ruby code does this correctly?

AFile.write('log.txt', 'New entry', append: true)
BFile.write('log.txt', 'New entry', 'a')
CFile.write('log.txt', 'New entry', flags: 'w')
DFile.write('log.txt', 'New entry', mode: 'a')
Attempts:
2 left
💡 Hint

File.write accepts options as a hash, and mode: 'a' means append.

🚀 Application
expert
3:00remaining
How many bytes are written and what is the file content after this code?

Consider this Ruby code:

bytes = File.write('data.txt', "Line1\nLine2\n", mode: 'w')
content = File.read('data.txt')

What are the values of bytes and content?

Ruby
bytes = File.write('data.txt', "Line1\nLine2\n", mode: 'w')
content = File.read('data.txt')
Abytes = 12, content = "Line1\nLine2\n"
Bbytes = 11, content = "Line1\nLine2"
Cbytes = 12, content = "Line1 Line2"
Dbytes = 10, content = "Line1\nLine2\n"
Attempts:
2 left
💡 Hint

Count characters including newline characters. File.write returns bytes written exactly.