0
0
Rubyprogramming~10 mins

File.open with block (auto-close) in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to open a file named 'example.txt' for reading.

Ruby
File.[1]('example.txt') do |file|
  puts file.read
end
Drag options to blanks, or click blank then click option'
Aopen
Bread
Cwrite
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'read' instead of 'open' as the method name.
Trying to manually close the file inside the block.
2fill in blank
medium

Complete the code to open 'data.txt' for writing inside a block.

Ruby
File.open('data.txt', [1]) do |file|
  file.puts 'Hello, world!'
end
Drag options to blanks, or click blank then click option'
A'r'
B'a'
C'w'
D'x'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'r' which is for reading only.
Using 'a' which appends instead of overwriting.
3fill in blank
hard

Fix the error in the code to properly open and auto-close 'log.txt' for appending.

Ruby
File.open('log.txt', [1]) do |file|
  file.puts 'New entry'
end
Drag options to blanks, or click blank then click option'
A'r'
B'rw'
C'w'
D'a'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' which overwrites the file.
Using 'r' which does not allow writing.
4fill in blank
hard

Fill both blanks to open 'notes.txt' for reading and print its content line by line.

Ruby
File.open('notes.txt', [1]) do |file|
  file.[2] do |line|
    puts line
  end
end
Drag options to blanks, or click blank then click option'
A'r'
Breadlines
Ceach_line
D'w'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode which is for writing.
Using 'readlines' which returns an array instead of iterating.
5fill in blank
hard

Fill all three blanks to open 'output.txt' for writing, write a line, and automatically close the file.

Ruby
File.[1]('output.txt', [2]) do |file|
  file.[3] 'This is a test.'
end
Drag options to blanks, or click blank then click option'
Aopen
B'w'
Cputs
Dread
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'read' instead of 'puts' to write.
Using mode 'r' which is for reading.