0

I want to read files that are in one directory, but the directory has another directory that has information that I also need to read. Anyone has an idea of how I can do that? Here's my directory tree

Root
   |__code
        |__ file.rb (where I am working from)
   |__Directory
      |__file 1
      |__file 2
      |__Directory 2
                 |__file 3
                 |__file 4

I'm using File.open("file1", "r") to open the files.

4
  • 1
    I assume you are running the script from within Directory. Did you try, for example, File.open("Directory2/file3", "r")? Commented Feb 14, 2019 at 12:31
  • @lurker no, I'm working in another directory called code, I have edited the tree. Commented Feb 14, 2019 at 12:54
  • The question text does not make it clear if you want to read all files that happen to be in the directory tree or some predefined file such as Root/Directory/Directory2/file3. Commented Feb 14, 2019 at 13:31
  • @LindaKadz if that's teh case, then File.open("file1", "r") won't necessarily work either. You'll need to work with a more explicit path. Commented Feb 14, 2019 at 13:54

1 Answer 1

1

Dir.glob is what you need. From Ruby Doc:

Expands pattern, which is a pattern string or an Array of pattern strings, and returns an array containing the matching filenames. If a block is given, calls the block once for each matching filename, passing the filename as a parameter to the block.

files = File.join("Root", "Directory", "**", "*")
Dir.glob(files)
# => ["Root/Directory/file 1", "Root/Directory/file 2", "Root/Directory 2/file 3", "Root/Directory 2/file 4"]
Sign up to request clarification or add additional context in comments.

4 Comments

what's the first argument in the File.join method?
I figured out what the first arguement is, I put the path to Directory and it listed for me all the files in the directory (that's file 1 and file 2), but not Directory 2. In fact, here's my output ` # [ "../Directory 1/file1.rb", "../Directory 1/file2.rb", "../Directory 1/file3.rb", "../Directory 1/file4.rb"]`
@LindaKadz I've just updated the answer to reflect the changes to the question. Please add the code you have been trying
This worked very well, but then I refactored to Dir.glob("../Directory 1/**/*.rb") Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.