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 contentWhat will be printed?
File.write('test.txt', 'Hello') content = File.read('test.txt') puts content
File.write writes the string to the file, and File.read reads it back.
The File.write method writes the string 'Hello' to 'test.txt'. Then File.read reads the content of the file, which is 'Hello'. So, puts prints 'Hello'.
Look at this Ruby code:
result = File.write('output.txt', 'Data')What is the value of result after this runs?
result = File.write('output.txt', 'Data')
File.write returns how many bytes it wrote to the file.
File.write returns the number of bytes written to the file. Since 'Data' has 4 characters, it returns 4.
What error does this Ruby code raise?
File.write(123, 'Hello')
File.write(123, 'Hello')
File.write expects a string filename, not a number.
File.write expects the first argument to be a string (filename). Passing an integer causes a TypeError because Ruby cannot convert Integer to String automatically.
You want to add text to the end of an existing file. Which Ruby code does this correctly?
File.write accepts options as a hash, and mode: 'a' means append.
To append text, you pass mode: 'a' as an option hash to File.write. Option D is invalid syntax, A uses a wrong option name, and D uses 'w' which overwrites the file.
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?
bytes = File.write('data.txt', "Line1\nLine2\n", mode: 'w') content = File.read('data.txt')
Count characters including newline characters. File.write returns bytes written exactly.
The string "Line1\nLine2\n" has 12 characters (5 + 1 + 5 + 1). File.write returns 12. The file content includes the newlines exactly as written.