Created
October 2, 2012 05:38
-
-
Save ryanlecompte/3816414 to your computer and use it in GitHub Desktop.
Shallow file finder
This file contains hidden or 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
require 'pathname' | |
# My answer to stackoverflow question posted here: | |
# http://stackoverflow.com/questions/12684736/a-twist-on-directory-walking-in-ruby | |
class ShallowFinder | |
def initialize(root) | |
@matches = {} | |
@root = Pathname(root) | |
end | |
def matches | |
while match = next_file | |
@matches[match.parent.to_s] = match | |
end | |
@matches.values | |
end | |
private | |
def next_file | |
@root.find do |entry| | |
Find.prune if previously_matched?(entry) | |
return entry if entry.file? | |
end | |
nil | |
end | |
def previously_matched?(entry) | |
return unless entry.directory? | |
@matches.key?(entry.to_s) | |
end | |
end | |
puts ShallowFinder.new('Root').matches |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment