O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required