Sorting by Size

Currently this program prints the file and directory names and their sizes in alphabetical order. But I am more interested in their relative sizes. It would, therefore, be more useful if the files were sorted by size rather than by name.

To be able to sort the files, you need some way of storing a complete list of all file sizes. One obvious way of doing this would be to add the file sizes to an array. In file_info2.rb, I create an empty array, $files, and each time a file is processed, I append its size to the array:

file_info2.rb

$files << fsize

I can then sort the file sizes to display low to high values or (by sorting and then reversing the array) to display from high to low values:

$files.sort # sort low to high $files.sort.reverse ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.