2

I want to store all the filenames inside a folder into an array. What's the best way to do this?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Linda
  • 1,203
  • 2
  • 15
  • 23
  • *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
  • 1
    Why 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 Answers3

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
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.

1

you can also use files=Dir.glob(*).

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
sunny1304
  • 1,684
  • 3
  • 17
  • 30