How to list files in directory with Ruby

Often you need to get files listing from some directory in your administrative tasks/scripts. It's really simple to list directories within Ruby code. I prefer to use Dir class. You can use it as shown below:

 files = Dir.glob("*") 

Returns all files from the current directory as an Array. You can iterate over every element very easy and use it for custom action.

If you need to list only some type of files - you must change globbing option - for example to list all jpeg files:
 
 Dir.glob('*.jpg') 

If you need to list files from other directory you can put absolute or relative path into glob method, i.e.:
 
 Dir.glob("/var/log/*") 

That's all for today. Thanks

Comments

wrote

Whoever wrote this, you know how to make a good atrilce.

Kaedn

Kaedn wrote

Perfect answer! That rlelay gets to the heart of it!

Comment