The code creates 'sample_dir' if it does not exist, so the directory will exist before listing entries.
Step 2: Understand Dir.entries output for empty directory
An empty directory still contains special entries: . (current directory) and .. (parent directory). So, Dir.entries returns [".", ".."].
Final Answer:
[".", ".."] -> Option C
Quick Check:
Empty directory entries = [".", ".."] [OK]
Hint: Empty dirs always show '.' and '..' in Dir.entries [OK]
Common Mistakes:
Expecting empty array for empty directory
Thinking directory name appears in entries
Assuming error if directory just created
4. Identify the error in this Ruby code snippet that tries to remove a directory:
Dir.rmdir('my_folder')
puts 'Folder removed'
medium
A. Dir.rmdir only removes non-empty directories
B. Dir.rmdir requires the directory to be empty before removal
C. Dir.rmdir should be Dir.remove
D. Dir.rmdir needs a block to execute
Solution
Step 1: Understand Dir.rmdir behavior
Dir.rmdir removes only empty directories. If 'my_folder' contains files or folders, it will raise an error.
Step 2: Check other options for correctness
Dir.rmdir only removes non-empty directories is wrong because it says the opposite. Dir.rmdir should be Dir.remove is invalid method name. Dir.rmdir needs a block to execute is incorrect; no block needed.
Final Answer:
Dir.rmdir requires the directory to be empty before removal -> Option B
Quick Check:
Dir.rmdir removes empty dirs only [OK]
Hint: Dir.rmdir only deletes empty directories [OK]
Common Mistakes:
Trying to remove non-empty directories with Dir.rmdir
Using wrong method name like Dir.remove
Expecting Dir.rmdir to accept a block
5. You want to change the current working directory to projects, create a new folder new_app inside it, and then list the contents of projects. Which sequence of Ruby commands correctly does this?
hard
A. Dir.chdir('projects')
Dir.mkdir('new_app')
puts Dir.entries('.')
B. Dir.mkdir('new_app')
Dir.chdir('projects')
puts Dir.entries('new_app')
C. Dir.entries('projects')
Dir.mkdir('new_app')
Dir.chdir('new_app')
D. Dir.chdir('new_app')
Dir.mkdir('projects')
puts Dir.entries('.')
Solution
Step 1: Change directory to 'projects'
Using Dir.chdir('projects') sets the current directory to 'projects'.
Step 2: Create 'new_app' inside 'projects'
Dir.mkdir('new_app') creates the new folder inside the current directory.
Step 3: List contents of current directory
Dir.entries('.') lists all files and folders inside 'projects', including 'new_app'.
Final Answer:
Dir.chdir('projects')
Dir.mkdir('new_app')
puts Dir.entries('.') -> Option A