30

I am new in ruby on rails and I want to read file names from a specified directory. Can anyone suggest code or any other links?

Thanks

warder57
  • 350
  • 5
  • 16
Adnan Khan
  • 897
  • 5
  • 14
  • 23
  • Possible duplicate of [Get names of all files from a folder with Ruby](http://stackoverflow.com/questions/1755665/get-names-of-all-files-from-a-folder-with-ruby) – Erwin Bolwidt Nov 04 '16 at 04:12
  • 2
    Please, don't be selfish and be grateful with the time people waste here to help you and at least accept a valid answer. People will not help you anymore if they see that you are that selfish. – Jorge Fuentes González Nov 12 '17 at 20:28

8 Answers8

33

I suggest you use Dir.entries("target_dir")

Check the documentation here

Stobbej
  • 1,080
  • 9
  • 17
25

If you want to get all file under particular folder in array:

files = Dir.glob("#{Rails.root}/private/**/*")

#=> ["/home/demo/private/sample_test.ods", "/home/demo/private/sample_test_two.ods", "/home/demo/private/sample_test_three.ods", "/home/demo/private/sample_test_one.ods"]
Sumit Munot
  • 3,748
  • 1
  • 32
  • 51
10

If you want to pull up a filtered list of files, you can also use Dir.glob:

Dir.glob("*.rb")
# => ["application.rb", "environment.rb"]
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
9

you can basically just get filenames with File.basename(file)

Dir.glob("path").map{ |s| File.basename(s) }
erimicel
  • 121
  • 1
  • 8
5

With Ruby on Rails, you should use Rails.root.join, it’s cleaner.

files = Dir.glob(Rails.root.join(‘path’, ‘to’, ‘folder’, '*'))

Then you get an array with files path.

cdmo
  • 1,239
  • 2
  • 14
  • 31
cercxtrova
  • 1,555
  • 13
  • 30
2

at first, you have to correctly create the path to your target folder

so example, when your target folder is 'models' in 'app' folder

target_folder_path = File.join(Rails.root, "/app/models")

and then this returns an array containing all of the filenames

Dir.children(target_folder_path)

also this code returns array without “.” and “..”

1

To list only filenames the most recommendable solution is:

irb(main)> Dir.children(Rails.root.join('app', 'models'))
=> ["user.rb", "post.rb", "comment.rb"]
Pere Joan Martorell
  • 2,608
  • 30
  • 29
0

If you're looking for relative paths from your Rails root folder, you can just use Dir, such as:

Dir["app/javascript/content/**/*"]

would return, for instance:

["app/javascript/content/Rails Models.md", "app/javascript/content/Rails Routing.md"]
Flavio Wuensche
  • 9,460
  • 1
  • 57
  • 54