0
0
Rubyprogramming~5 mins

File.open with block (auto-close) in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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
end
Click 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!'
end
Click to reveal answer
What does File.open('data.txt', 'r') do |f| ... end do?
AOpens 'data.txt' for reading and closes it automatically after the block.
BOpens 'data.txt' for writing and never closes it.
CCreates a new file named 'data.txt'.
DDeletes 'data.txt' after reading.
What happens if an error occurs inside the block passed to File.open?
AThe file remains open and causes a leak.
BThe program crashes without closing the file.
CThe file is still closed automatically.
DThe file is deleted.
Which mode should you use with File.open to write new content to a file?
A'w'
B'a'
C'r'
D'x'
What will happen if you try to read from the file outside the block after File.open with a block?
AIt will read the file normally.
BIt will raise an error because the file is closed.
CIt will create a new file.
DIt will append data to the file.
Which of these is a benefit of using File.open with a block?
AIt deletes the file after use.
BYou must manually close the file.
CThe file stays open for the whole program.
DThe file is automatically closed after the block.
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.