Recall & Review
beginner
What does
File.open with a block do in Ruby?It opens a file, runs the code inside the block using the file, and then automatically closes the file when the block finishes.
Click to reveal answer
beginner
Why is using
File.open with a block safer than opening and closing files manually?Because it ensures the file is always closed properly, even if an error happens inside the block.
Click to reveal answer
beginner
Show the syntax of
File.open with a block to read a file named 'example.txt'.File.open('example.txt', 'r') do |file|
content = file.read
puts content
endClick to reveal answer
intermediate
What happens if you try to use the file outside the block when using
File.open with a block?The file is already closed, so trying to read or write will cause an error.
Click to reveal answer
beginner
Can you write to a file using
File.open with a block? How?Yes. Open the file with write mode ('w') and use the block to write inside it. Example:
File.open('output.txt', 'w') do |file|
file.puts 'Hello!'
endClick to reveal answer
What does
File.open('data.txt', 'r') do |f| ... end do?✗ Incorrect
Using File.open with a block opens the file and closes it automatically after the block finishes.
What happens if an error occurs inside the block passed to
File.open?✗ Incorrect
Ruby ensures the file is closed even if an error happens inside the block.
Which mode should you use with
File.open to write new content to a file?✗ Incorrect
'w' mode opens the file for writing and overwrites existing content.
What will happen if you try to read from the file outside the block after
File.open with a block?✗ Incorrect
The file is closed after the block, so reading outside causes an error.
Which of these is a benefit of using
File.open with a block?✗ Incorrect
The block form automatically closes the file, making code safer and cleaner.
Explain how
File.open with a block works and why it is useful.Think about what happens before, during, and after the block.
You got /4 concepts.
Write a simple Ruby code snippet using
File.open with a block to read and print a file's content.Use 'r' mode and a block with |file| parameter.
You got /4 concepts.