28

Does anyone know if there's an existing module/function inside Ruby to traverse file system directories and files? I'm looking for something similar to Python's os.walk. The closest module I've found is Find but requires some extra work to do the traversal.

The Python code looks like the following:

for root, dirs, files in os.walk('.'):
    for name in files:
        print name
    for name in dirs:
        print name
Ken Liu
  • 22,503
  • 19
  • 75
  • 98
Thierry Lam
  • 45,304
  • 42
  • 117
  • 144

3 Answers3

27

The following will print all files recursively. Then you can use File.directory? to see if the it is a directory or a file.

Dir['**/*'].each { |f| print f }
ACoolie
  • 1,429
  • 1
  • 12
  • 16
11

Find seems pretty simple to me:

require "find"
Find.find('mydir'){|f| puts f}
webwurst
  • 4,830
  • 3
  • 23
  • 32
Ken Liu
  • 22,503
  • 19
  • 75
  • 98
  • And where is `Find` defined? `require "find"` Here is the docs: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/find/rdoc/Find.html – Sukima May 01 '13 at 16:49
5
require 'pathname'

def os_walk(dir)
  root = Pathname(dir)
  files, dirs = [], []
  Pathname(root).find do |path|
    unless path == root
      dirs << path if path.directory?
      files << path if path.file?
    end
  end
  [root, files, dirs]
end

root, files, dirs = os_walk('.')
tig
  • 25,841
  • 10
  • 64
  • 96