Cover by Leonard Richardson, Lucas Carlson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

6.5. Listing a Directory

Problem

You want to list or process the files or subdirectories within a directory.

Solution

If you're starting from a directory name, you can use Dir.entries to get an array of the items in the directory, or Dir.foreach to iterate over the items. Here's an exampleof each run on a sample directory:

	# See the chapter intro to get the create_tree library
	require 'create_tree'
	create_tree 'mydir' =>
	  [ {'subdirectory' => [['file_in_subdirectory', 'Just a simple file.']] },
	  '.hidden_file', 'ruby_script.rb', 'text_file' ] 
Dir.entries('mydir')
	
	# => [".", "..", ".hidden_file", "ruby_script.rb", "subdirectory",
	# "text_file"]
	
	 
Dir.foreach('mydir') { |x| puts x if x != "." && x != ".."}
	# .hidden_file
	# ruby_script.rb
	# subdirectory
	# text_file

You can also use Dir[] to pick up all files matching a certain pattern, using a format similar to the bash shell's glob format (and somewhat less similar to the wildcard format used by the Windows command-line shell):

	# Find all the "regular" files and subdirectories in mydir. This excludes
	# hidden files, and the special directories . and ..
	Dir["mydir/*"]
	# => ["mydir/ruby_script.rb", "mydir/subdirectory", "mydir/text_file"]
	
	# Find all the .rb files in mydir
	Dir["mydir/*.rb"]                 # =>  ["mydir/ruby_script.rb"]

You can also open a directory handle with Dir#open, and treat it like any other Enumerable. Methods like each,each_with_index, grep, and reject will all work (but see below if you want to call them more than once). As with ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required