Consider the following Ruby code snippet:
File.open("test.txt", "w") do |file|
file.puts "Hello, world!"
end
puts File.exist?("test.txt")What will be printed when this code runs?
File.open("test.txt", "w") do |file| file.puts "Hello, world!" end puts File.exist?("test.txt")
Think about whether the file is created and closed properly after the block.
The File.open method with a block automatically closes the file after the block finishes. The file "test.txt" is created and written to, so File.exist?("test.txt") returns true.
Given a file "data.txt" containing the text "Ruby Rocks!", what will this code output?
File.open("data.txt", "r") do |file|
puts file.read
endFile.open("data.txt", "r") do |file| puts file.read end
Remember that file.read reads the entire content of the file.
The block reads the entire content of "data.txt" and prints it. Since the file contains "Ruby Rocks!", that is printed.
What happens when you run this Ruby code?
file = File.open("example.txt", "w")
file.puts "Hello"
# No file.close calledfile = File.open("example.txt", "w") file.puts "Hello"
Think about what happens if you don't explicitly close a file in Ruby.
If you open a file without a block and don't close it, Ruby does not raise an error immediately. The file stays open until the program ends or the object is garbage collected. This can cause resource leaks but no immediate error.
Which of the following is the main advantage of using File.open with a block?
Think about resource management and safety.
Using File.open with a block ensures the file is closed automatically after the block ends, preventing resource leaks and errors from forgetting to close the file.
Consider this Ruby code:
begin
File.open("missing.txt", "r") do |file|
puts file.read
end
rescue Errno::ENOENT
puts "File not found"
endWhat will be printed when this code runs and the file "missing.txt" does not exist?
begin File.open("missing.txt", "r") do |file| puts file.read end rescue Errno::ENOENT puts "File not found" end
Think about how exceptions are handled in Ruby.
The code tries to open a file that does not exist. This raises Errno::ENOENT, which is rescued and prints "File not found".