0
0
Rubyprogramming~10 mins

Why file handling matters in Ruby - Test Your Understanding

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 = File.[1]('example.txt')
Drag options to blanks, or click blank then click option'
Awrite
Bread
Copen
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'read' instead of 'open' to start working with a file.
Trying to 'close' a file before opening it.
2fill in blank
medium

Complete the code to write the string 'Hello' to a file.

Ruby
File.open('greeting.txt', 'w') do |file|
  file.[1]('Hello')
end
Drag options to blanks, or click blank then click option'
Awrite
Bread
Cputs
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'read' which is for reading, not writing.
Using 'close' inside the block, which is handled automatically.
3fill in blank
hard

Fix the error in the code to read all lines from a file.

Ruby
lines = File.[1]('data.txt').readlines
Drag options to blanks, or click blank then click option'
Aputs
Bopen
Cclose
Dwrite
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to call 'readlines' directly on 'write' or 'close'.
Using 'puts' which is for output, not file access.
4fill in blank
hard

Fill both blanks to create a hash with words as keys and their lengths as values, only for words longer than 3 characters.

Ruby
lengths = {word: word.[1] for word in words if word.[2] > 3}
Drag options to blanks, or click blank then click option'
Alength
Bsize
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'size' instead of 'length'.
Using '<' instead of '>' for filtering.
5fill in blank
hard

Fill all three blanks to create a hash with uppercase words as keys and their lengths as values, only for words longer than 4 characters.

Ruby
result = {word.[1]: word.[2] for word in words if word.[3] > 4}
Drag options to blanks, or click blank then click option'
Aupcase
Bsize
C>
Ddowncase
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'downcase' instead of 'upcase'.
Using '<' instead of '>' for filtering.