Ruby directory list - How to use Ruby to list files in a directory

It's so easy with Ruby to get a list of files in the current directory that I hesitate to write this, but hey, this blog is for me and my bad memory, so here's a quick note on how to use Ruby to get a list of files of a certain type in a directory.

To have a little fun with this, I'll use irb (the interactive Ruby shell environment) to show how to do this.

Using irb

First, if you've never used irb before, it's very easy. Assuming you already have Ruby installed, from a shell window (Unix, Linux, Mac, or even a DOS shell on Windows), just type irb, like this:

$ irb

>>

The new >> prompt comes from Ruby, more specifically, the irb environment that you are now in. From here you can type any regular Ruby command, so now I'll show how to list all the JPG files in the current directory.

How to list selected files in the current directory

In the sequence that follows, the text I type is shown in a bold font, and the rest of the text comes from the irb shell environment:

$ irb

>> basedir = '.'
=> "."

>> files = Dir.glob("*.jpg")
=> ["disk-inventory-x-1.jpg", "disk-inventory-x-2.jpg", "omni-disk-sweeper-1.jpg"]

>> puts files
disk-inventory-x-1.jpg
disk-inventory-x-2.jpg
omni-disk-sweeper-1.jpg

=> nil

As you can see from that code, all I have to do to get a list of the JPG files in the current directory is write a few lines of code, like this:

basedir = '.'
files = Dir.glob("*.jpg")

How to list all the files in the current directory

After that I can use puts or any other Ruby command to work with the files array.

If you want to get a list of all the files in the current directory, just change your glob pattern, like this:

files = Dir.glob("*")

 

Thanks! Dir.glob works!

Thanks! Dir.glob works! Simple and easy.

Post new comment

The content of this field is kept private and will not be shown publicly.