Blog

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

How to check that variable is defined

There are minimu two ways. First - by using defined? method:

 if defined? my_var puts "exists" else puts "doesn't exist" end 

defined? method returns type of variable if variable exists and nil otherwise. Second way is by initializing variable which you want to check ...

It cost nothing - so that way it looks like that:
 
 my_var = nil if my_var.nil? #logic goes here else #otherwise end