I want to store all the filenames inside a folder into an array. What's the best way to do this?
Asked
Active
Viewed 4,359 times
2
-
*WHY* do you want to read all the filenames in at once? That isn't a scalable solution since it's possible for a folder to contain many thousands of files. – the Tin Man Mar 08 '13 at 14:10
-
These are .conf files created in apache2/sites-enabled. My guess is 3-10 files. – Linda Mar 11 '13 at 08:58
-
1Why is this not a "real" question? And who cares "why" the OP wants this? Here's an identical question that has been marked as useful >200 times, and its accepted answer (`Dir["/path/to/search/*"]`) is marked as useful >300 times... https://stackoverflow.com/questions/1755665/get-names-of-all-files-from-a-folder-with-ruby <-- better mark it as **not real** too! muhaha! use your power! put someone down! feel good about yourself! Yeah! – user664833 Feb 21 '17 at 04:21
3 Answers
5
You can use this:
files = Dir.foreach(dir).select { |x| File.file?("#{dir}/#{x}") }
This returns the filenames, i.e. without folder.
If you need the complete path, use something like this:
files = Dir.foreach(dir) \
.map { |x| File.expand_path("#{dir}/#{x}") } \
.select { |x| File.file?(x) }

Daniel Hilgarth
- 171,043
- 40
- 335
- 443
-
-
@Kate: As you request, this gives you the filenames inside a folder. If you want the full path, you need to use the second version from my updated answer. – Daniel Hilgarth Mar 08 '13 at 11:19
-
-
@Kate: Please see update. My previous versions failed when `dir` was anything other than the current directory. – Daniel Hilgarth Mar 08 '13 at 11:32
-
2
You can use:
files = Dir.entries(directory)
that returns an array containing all the filenames in the given directory.
Take a look in the Ruby Doc for more information.

Michael Fürstenberg
- 756
- 3
- 9