Skip to content

Instantly share code, notes, and snippets.

@DavidJRobertson
Created December 11, 2012 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidJRobertson/4260680 to your computer and use it in GitHub Desktop.
Save DavidJRobertson/4260680 to your computer and use it in GitHub Desktop.
Ruby: pretty directory recursion :P
# EDIT: this can actually be done more simply like this:
Dir.foreach("path/to/directory/**/*") do |item|
next if File.directory? item
# Do whatever with item now
end
# Define this somewhere
def each_file(dir = ".", &block)
Dir.foreach(dir) do |item|
next if item == '.' or item == '..'
path = File.join dir, item
unless File.directory? path
yield path
else
each_file path, &block
end
end
end
# Then, whenever you want to recurse through all files and subdirectories in a directory...
each_file "path/to/directory" do |filename|
puts filename
end
# Or, if we just want to go through the current directory
each_file do |filename|
puts filename
end
# If we were to monkey patch the built-in Dir class like this...
class Dir
def self.each_r(dir = ".", &block)
foreach(dir) do |item|
next if item == '.' or item == '..'
path = File.join dir, item
unless File.directory? path
yield path
else
each_r path, &block
end
end
end
end
# ... then we could just do this:
Dir.each_r "path/to/dir" do |filename|
puts filename
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment