What's the Ruby equivalent of Python's os.walk?

Question:

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
Asked By: Thierry Lam

||

Answers:

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 }
Answered By: ACoolie

Find seems pretty simple to me:

require "find"
Find.find('mydir'){|f| puts f}
Answered By: Ken Liu
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('.')
Answered By: tig
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.