Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

ruby

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
like image 206
Thierry Lam Avatar asked Aug 15 '09 03:08

Thierry Lam


People also ask

Is OS walk a depth first?

os. walk() will traverse this directory tree using the depth-first search algorithm.

What is walk in Python?

Python method walk() generates the file names in a directory tree by walking the tree either top-down or bottom-up.


3 Answers

Find seems pretty simple to me:

require "find"
Find.find('mydir'){|f| puts f}
like image 32
Ken Liu Avatar answered Oct 14 '22 19:10

Ken Liu


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 }
like image 68
ACoolie Avatar answered Oct 14 '22 20:10

ACoolie


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('.')
like image 5
tig Avatar answered Oct 14 '22 21:10

tig