1 minute read

Often, you may need to obtain a listing of files from a specific directory for your administrative tasks or scripts. Fortunately, it’s quite simple to accomplish this using Ruby code. In this article, we will explore how to list files using the Dir class in Ruby. To retrieve a list of all files in the current directory, you can use the following code snippet:

files = Dir.glob("*")

The Dir.glob method with the argument "*" returns an array containing all files in the current directory. You can easily iterate over each element in the array and perform custom actions based on your requirements.

Filtering Files by Type

If you need to list only files of a specific type, you can modify the globbing pattern accordingly. For example, to list all JPEG files, you can use the following code:

Dir.glob("*.jpg")

This modified globbing pattern will return an array containing only the JPEG files in the current directory.

Listing Files from Another Directory

In case you want to list files from a directory other than the current one, you can provide either an absolute or relative path to the glob method. Here’s an example:

Dir.glob("/var/log/*")

In the above code snippet, the globbing pattern "/var/log/*" will retrieve a list of all files within the /var/log directory.

That’s all for today. Thank you for reading!