Skip to content

Instantly share code, notes, and snippets.

@ryanlecompte
Created October 2, 2012 05:38
Show Gist options
  • Save ryanlecompte/3816414 to your computer and use it in GitHub Desktop.
Save ryanlecompte/3816414 to your computer and use it in GitHub Desktop.
Shallow file finder
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