I want to get all file names from a folder using Ruby.
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")
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
Dir.new('/home/user/foldername').each { |file| puts file }
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.
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
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