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

前端 未结 3 1900
逝去的感伤
逝去的感伤 2021-01-01 10:33

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

相关标签:
3条回答
  • 2021-01-01 11:16

    Find seems pretty simple to me:

    require "find"
    Find.find('mydir'){|f| puts f}
    
    0 讨论(0)
  • 2021-01-01 11:23
    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('.')
    
    0 讨论(0)
  • 2021-01-01 11:28

    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 }
    
    0 讨论(0)
提交回复
热议问题