Created
December 11, 2012 18:00
-
-
Save DavidJRobertson/4260680 to your computer and use it in GitHub Desktop.
Ruby: pretty directory recursion :P
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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