Challenge - 5 Problems
Ruby Dir Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Ruby code using Dir.entries?
Consider the following Ruby code snippet that lists entries in the current directory. What will it output?
Ruby
puts Dir.entries(".").sort
Attempts:
2 left
💡 Hint
Dir.entries returns all entries including special ones '.' and '..'.
✗ Incorrect
Dir.entries returns all entries in the directory including '.' (current directory) and '..' (parent directory). Sorting them alphabetically will include these special entries.
❓ Predict Output
intermediateWhat does Dir.glob("*.rb") return?
Given a directory with files: test.rb, example.py, script.rb, and README.md, what will Dir.glob("*.rb") return?
Ruby
p Dir.glob("*.rb")
Attempts:
2 left
💡 Hint
Dir.glob with '*.rb' matches files ending with .rb only.
✗ Incorrect
Dir.glob("*.rb") returns an array of filenames in the current directory that match the pattern '*.rb'. Only test.rb and script.rb match.
🔧 Debug
advancedWhy does this code raise an error?
This Ruby code tries to change directory and list files but raises an error. Identify the cause.
Ruby
Dir.chdir("nonexistent_dir") puts Dir.entries(".")
Attempts:
2 left
💡 Hint
Check if the directory exists before changing into it.
✗ Incorrect
Dir.chdir raises Errno::ENOENT if the directory does not exist. The error is due to trying to change into a non-existing directory.
📝 Syntax
advancedWhich option correctly creates a new directory named 'data'?
Select the Ruby code that correctly creates a directory named 'data' in the current working directory.
Attempts:
2 left
💡 Hint
The method to create a directory is mkdir.
✗ Incorrect
Dir.mkdir('data') creates a new directory named 'data'. Other methods do not exist or do not create directories.
🚀 Application
expertHow many entries will this code print?
Given a directory containing 3 files and 2 subdirectories (excluding '.' and '..'), what will this Ruby code print?
Ruby
entries = Dir.entries(".") - ['.', '..'] puts entries.size
Attempts:
2 left
💡 Hint
Dir.entries includes '.' and '..', which are removed here.
✗ Incorrect
Dir.entries returns all entries including '.' and '..'. Removing these two leaves the actual files and directories. Since there are 3 files and 2 directories, total is 5.
