Ruby - File Directory Listing

Introduction

Get a list of the files and directories within a specific directory using Dir.entries:

Demo

puts Dir.entries("c:/").join(' ')

Result

Dir.entries returns an array with all the entries within the specified directory.

Dir.foreach provides the same feature, but as an iterator:

Demo

Dir.foreach("c:/") do |entry| 
  puts entry 
end

Result

An even more concise way of getting directory listings is by using Dir's class array method:

Demo

puts Dir["c:/*"]

Result

Here, each entry is returned as an absolute filename.

You could take this process a step further and be a little more platform independent:

Demo

Dir[File.join(File::SEPARATOR, 'c:/', 'test', '*')]

Related Topic