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

3

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
Sclerous answered 15/8, 2009 at 3:40 Comment(0)
P
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 }
Pediment answered 15/8, 2009 at 3:51 Comment(4)
Instead of Dir[foo].each { bar }, you can use Dir.glob(foo) { bar } which will iterate over all the files matching the block without creating a temporary array first.Crusty
Is Dir.foreach('.') { |f| print f } the same? It looks more expressive than the [] version.Sclerous
@Thierry: No. Dir.foreach does not enter subdirectories.Crusty
I like the glob, you can cherry pick the files you wantSclerous
J
11

Find seems pretty simple to me:

require "find"
Find.find('mydir'){|f| puts f}
Julejulee answered 15/8, 2009 at 5:17 Comment(1)
And where is Find defined? require "find" Here is the docs: ruby-doc.org/stdlib-1.9.3/libdoc/find/rdoc/Find.htmlOrest
A
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('.')
Avoidance answered 15/8, 2009 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.