Cover by Huw Collingbourne

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required