Get names of all files from a folder with Ruby

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

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

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

    In an IRB context, you can use the following to get the files in the current directory:

    file_names = `ls`.split("\n")
    

    You can make this work on other directories too:

    file_names = `ls ~/Documents`.split("\n")
    
    0 讨论(0)
  • 2020-11-29 15:35

    Personally, I found this the most useful for looping over files in a folder, forward looking safety:

    Dir['/etc/path/*'].each do |file_name|
      next if File.directory? file_name 
    end
    
    0 讨论(0)
  • 2020-11-29 15:37
    Dir.new('/home/user/foldername').each { |file| puts file }
    
    0 讨论(0)
  • 2020-11-29 15:39

    If you want get an array of filenames including symlinks, use

    Dir.new('/path/to/dir').entries.reject { |f| File.directory? f }
    

    or even

    Dir.new('/path/to/dir').reject { |f| File.directory? f }
    

    and if you want to go without symlinks, use

    Dir.new('/path/to/dir').select { |f| File.file? f }
    

    As shown in other answers, use Dir.glob('/path/to/dir/**/*') instead of Dir.new('/path/to/dir') if you want to get all the files recursively.

    0 讨论(0)
  • 2020-11-29 15:41

    One simple way could be:

    dir = './' # desired directory
    files = Dir.glob(File.join(dir, '**', '*')).select{|file| File.file?(file)}
    
    files.each do |f|
        puts f
    end
    
    0 讨论(0)
  • 2020-11-29 15:42

    In Ruby 2.5 you can now use Dir.children. It gets filenames as an array except for "." and ".."

    Example:

    Dir.children("testdir")   #=> ["config.h", "main.rb"]
    

    http://ruby-doc.org/core-2.5.0/Dir.html#method-c-children

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