Get names of all files from a folder with Ruby

后端 未结 19 2194
[愿得一人]
[愿得一人] 2020-11-29 14:57

I want to get all file names from a folder using Ruby.

相关标签:
19条回答
  • 2020-11-29 15:57

    This works for me:

    If you don't want hidden files[1], use Dir[]:

    # With a relative path, Dir[] will return relative paths 
    # as `[ './myfile', ... ]`
    #
    Dir[ './*' ].select{ |f| File.file? f } 
    
    # Want just the filename?
    # as: [ 'myfile', ... ]
    #
    Dir[ '../*' ].select{ |f| File.file? f }.map{ |f| File.basename f }
    
    # Turn them into absolute paths?
    # [ '/path/to/myfile', ... ]
    #
    Dir[ '../*' ].select{ |f| File.file? f }.map{ |f| File.absolute_path f }
    
    # With an absolute path, Dir[] will return absolute paths:
    # as: [ '/home/../home/test/myfile', ... ]
    #
    Dir[ '/home/../home/test/*' ].select{ |f| File.file? f }
    
    # Need the paths to be canonical?
    # as: [ '/home/test/myfile', ... ]
    #
    Dir[ '/home/../home/test/*' ].select{ |f| File.file? f }.map{ |f| File.expand_path f }
    

    Now, Dir.entries will return hidden files, and you don't need the wildcard asterix (you can just pass the variable with the directory name), but it will return the basename directly, so the File.xxx functions won't work.

    # In the current working dir:
    #
    Dir.entries( '.' ).select{ |f| File.file? f }
    
    # In another directory, relative or otherwise, you need to transform the path 
    # so it is either absolute, or relative to the current working dir to call File.xxx functions:
    #
    home = "/home/test"
    Dir.entries( home ).select{ |f| File.file? File.join( home, f ) }
    

    [1] .dotfile on unix, I don't know about Windows

    0 讨论(0)
提交回复
热议问题