user3658307 user3658307 - 7 months ago 56
Ruby Question

Check if file/folder is in a subdirectory in Ruby

What's the nicest way to check if a given file/directory is in some other directory (or one of its subdirectories)? Platform-independence and absolute/relative path handling would be nice.

One easy way is just to search through the files and check each time, but maybe there is a better one.

e.g. given directory

, is
anywhere in the directory subtree rooted at
, i.e.
or something.


A nice and quickly way is to use glob method provided by Dir class in the Ruby stdlib.

glob( pattern, [flags] ) # => matches

Expands pattern, which is an Array of patterns or a pattern String, and returns the results as matches or as arguments given to the block.

Works both with file and directory and allow you to search recursively. It returns an array with the files/dirs which match the pattern, it will be empty if no one matches.

root = '/my_root'
value = 'et_voila.txt'


# ** Matches directories recursively.

# or you can pass also the relative path