0
0
Rubyprogramming~20 mins

File.open with block (auto-close) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Handling Mastery
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.open with a block?

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?

Ruby
File.open("test.txt", "w") do |file|
  file.puts "Hello, world!"
end
puts File.exist?("test.txt")
Anil
Btrue
Cfalse
DAn error is raised
Attempts:
2 left
💡 Hint

Think about whether the file is created and closed properly after the block.

Predict Output
intermediate
2:00remaining
What does this code print when reading a file with File.open and a block?

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
end
Ruby
File.open("data.txt", "r") do |file|
  puts file.read
end
AAn error is raised
BAn empty line
CRuby Rocks!
Dnil
Attempts:
2 left
💡 Hint

Remember that file.read reads the entire content of the file.

Predict Output
advanced
2:00remaining
What error does this code raise when using File.open without a block but forgetting to close?

What happens when you run this Ruby code?

file = File.open("example.txt", "w")
file.puts "Hello"
# No file.close called
Ruby
file = File.open("example.txt", "w")
file.puts "Hello"
AIOError: not closed
BRuntimeError: closed stream
CSyntaxError
DNo error, but file remains open until program ends
Attempts:
2 left
💡 Hint

Think about what happens if you don't explicitly close a file in Ruby.

🧠 Conceptual
advanced
1:30remaining
Why is using File.open with a block preferred over without a block?

Which of the following is the main advantage of using File.open with a block?

AIt automatically closes the file after the block finishes
BIt speeds up file reading
CIt prevents any errors from occurring
DIt makes the file read-only
Attempts:
2 left
💡 Hint

Think about resource management and safety.

Predict Output
expert
2:30remaining
What is the output of this Ruby code using File.open with a block and exception handling?

Consider this Ruby code:

begin
  File.open("missing.txt", "r") do |file|
    puts file.read
  end
rescue Errno::ENOENT
  puts "File not found"
end

What will be printed when this code runs and the file "missing.txt" does not exist?

Ruby
begin
  File.open("missing.txt", "r") do |file|
    puts file.read
  end
rescue Errno::ENOENT
  puts "File not found"
end
AFile not found
Bnil
CAn unhandled exception is raised
DAn empty line
Attempts:
2 left
💡 Hint

Think about how exceptions are handled in Ruby.