Understanding disk usage is crucial for system administration and application optimization. This drill teaches you to recursively traverse directories, calculate file sizes, filter by file types, and format output for human readability. You'll learn recursive algorithms, directory traversal, file metadata access, and data formattingβessential skills for building DevOps tools, backup systems, and disk usage analyzers.
Find.find(path) recursively yields every file and directory
File.directory?(path) checks if path is a directory
File.size(path) returns file size in bytes
File.extname(path) returns extension including the dot (e.g., '.txt')
Use 'next' to skip directories in the Find.find loop
Hash.new { |h, k| h[k] = { size: 0, count: 0 } } creates nested default hash
Sort by size descending: array.sort_by { |k, v| -v[:size] }
1024 bytes = 1 KB, 1024 KB = 1 MB, 1024 MB = 1 GB
analyze_directory('config.txt')
DIRECTORY SIZE ANALYSIS Directory: /test_dir ================================================== BY FILE TYPE .txt: 2.81 KB (3 files) .rb: 500 bytes (1 files) .json: 300 bytes (1 files) -------------------------------------------------- SUMMARY Total Files: 5 Total Size: 3.59 KB
analyze_directory('config.txt')
DIRECTORY SIZE ANALYSIS Directory: /large_dir ================================================== BY FILE TYPE .mp4: 2.38 MB (1 files) .jpg: 1.43 MB (1 files) .pdf: 488.28 KB (1 files) -------------------------------------------------- SUMMARY Total Files: 3 Total Size: 4.29 MB
analyze_directory('config.txt')
DIRECTORY SIZE ANALYSIS Directory: /mixed_dir ================================================== BY FILE TYPE No extension: 1.46 KB (2 files) .txt: 300 bytes (1 files) -------------------------------------------------- SUMMARY Total Files: 3 Total Size: 1.76 KB
Console output will appear here...
Are you sure?
You're making great progress