Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

Dir.glob

(::array[::path] | ::path pattern, ?::int flags, ?base: ::path?, ?sort: bool) -> ::Array[::String]
(::array[::path] | ::path pattern, ?::int flags, ?base: ::path?, ?sort: bool) { (::String pathname) -> void } -> nil
Dir.glob(*patterns, flags: 0, base: nil, sort: true) → array
Dir.glob(*patterns, flags: 0, base: nil, sort: true) {|entry_name| ... } → nil

Forms an array entry_names of the entry names selected by the arguments.

Argument patterns is a string pattern or an array of string patterns; note that these are not regexps; see below.

Notes for the following examples:

  • '*' is the pattern that matches any entry name except those that begin with '.'.

  • We use method Array#take to shorten returned arrays that otherwise would be very large.

With no block, returns array entry_names; example (using the simple file tree):

Example
Dir.glob('*') # => ["config.h", "lib", "main.rb"]

With a block, calls the block with each of the entry_names and returns nil:

Example
Dir.glob('*') {|entry_name| puts entry_name } # => nil

Output:

Example
config.h
lib
main.rb

If optional keyword argument flags is given, the value modifies the matching; see below.

If optional keyword argument base is given, its value specifies the base directory. Each pattern string specifies entries relative to the base directory; the default is '.'. The base directory is not prepended to the entry names in the result:

Example
Dir.glob(pattern, base: 'lib').take(5)
# => ["abbrev.gemspec", "abbrev.rb", "base64.gemspec", "base64.rb", "benchmark.gemspec"]
Dir.glob(pattern, base: 'lib/irb').take(5)
# => ["cmd", "color.rb", "color_printer.rb", "completion.rb", "context.rb"]

If optional keyword sort is given, its value specifies whether the array is to be sorted; the default is true. Passing value false with that keyword disables sorting (though the underlying file system may already have sorted the array).

Patterns

Each pattern string is expanded according to certain metacharacters; examples below use the Ruby file tree:

  • '*': Matches any substring in an entry name, similar in meaning to regexp /.*/mx; may be restricted by other values in the pattern strings:

    • '*' matches all entry names:

      Example
      Dir.glob('*').take(3)  # => ["BSDL", "CONTRIBUTING.md", "COPYING"]
      
    • 'c*' matches entry names beginning with 'c':

      Example
      Dir.glob('c*').take(3) # => ["CONTRIBUTING.md", "COPYING", "COPYING.ja"]
      
    • '*c' matches entry names ending with 'c':

      Example
      Dir.glob('*c').take(3) # => ["addr2line.c", "array.c", "ast.c"]
      
    • '*c*' matches entry names that contain 'c', even at the beginning or end:

      Example
      Dir.glob('*c*').take(3) # => ["CONTRIBUTING.md", "COPYING", "COPYING.ja"]
      

    Does not match Unix-like hidden entry names (“dot files”). To include those in the matched entry names, use flag IO::FNM_DOTMATCH or something like '{*,.*}'.

  • '**': Matches entry names recursively if followed by the slash character '/':

    Example
    Dir.glob('**/').take(3) # => ["basictest/", "benchmark/", "benchmark/gc/"]
    

    If the string pattern contains other characters or is not followed by a slash character, it is equivalent to '*'.

  • '?' Matches any single character; similar in meaning to regexp /./:

    Example
    Dir.glob('io.?') # => ["io.c"]
    
  • '[_set_]': Matches any one character in the string set; behaves like a Regexp character class, including set negation ('[^a-z]'):

    Example
    Dir.glob('*.[a-z][a-z]').take(3)
    # => ["CONTRIBUTING.md", "COPYING.ja", "KNOWNBUGS.rb"]
    
  • '{_abc_,_xyz_}': Matches either string abc or string xyz; behaves like Regexp alternation:

    Example
    Dir.glob('{LEGAL,BSDL}') # => ["LEGAL", "BSDL"]
    

    More than two alternatives may be given.

  • \: Escapes the following metacharacter.

    Note that on Windows, the backslash character may not be used in a string pattern: Dir['c:\foo*'] will not work, use Dir['c:/foo*'] instead.

More examples (using the simple file tree):

# We're in the example directory.
File.basename(Dir.pwd) # => "example"
Dir.glob('config.?')              # => ["config.h"]
Dir.glob('*.[a-z][a-z]')          # => ["main.rb"]
Dir.glob('*.[^r]*')               # => ["config.h"]
Dir.glob('*.{rb,h}')              # => ["main.rb", "config.h"]
Dir.glob('*')                     # => ["config.h", "lib", "main.rb"]
Dir.glob('*', File::FNM_DOTMATCH) # => [".", "config.h", "lib", "main.rb"]
Dir.glob(["*.rb", "*.h"])         # => ["main.rb", "config.h"]

Dir.glob('**/*.rb')
=> ["lib/song/karaoke.rb", "lib/song.rb", "main.rb"]

Dir.glob('**/*.rb', base: 'lib')  #   => ["song/karaoke.rb", "song.rb"]

Dir.glob('**/lib')                # => ["lib"]

Dir.glob('**/lib/**/*.rb')        # => ["lib/song/karaoke.rb", "lib/song.rb"]

Dir.glob('**/lib/*.rb')           # => ["lib/song.rb"]

Flags

If optional keyword argument flags is given (the default is zero – no flags), its value should be the bitwise OR of one or more of the constants defined in module File::Constants.

Example:

Example
flags = File::FNM_EXTGLOB | File::FNM_DOTMATCH

Specifying flags can extend, restrict, or otherwise modify the matching.

The flags for this method (other constants in File::Constants do not apply):

  • File::FNM_DOTMATCH: specifies that entry names beginning with '.' should be considered for matching:

    Example
    Dir.glob('*').take(5)
    # => ["BSDL", "CONTRIBUTING.md", "COPYING", "COPYING.ja", "GPL"]
    Dir.glob('*', flags: File::FNM_DOTMATCH).take(5)
    # => [".", ".appveyor.yml", ".cirrus.yml", ".dir-locals.el", ".document"]
    
  • File::FNM_EXTGLOB: enables the pattern extension '{_a_,_b_}', which matches pattern a and pattern b; behaves like a regexp union (e.g., '(?:_a_|_b_)'):

    Example
    pattern = '{LEGAL,BSDL}'
    Dir.glob(pattern)      # => ["LEGAL", "BSDL"]
    
  • File::FNM_NOESCAPE: specifies that escaping with the backslash character '\' is disabled; the character is not an escape character.

  • File::FNM_PATHNAME: specifies that metacharacters '*' and '?' do not match directory separators.

  • File::FNM_SHORTNAME: specifies that patterns may match short names if they exist; Windows only.

Ruby version changes

  1. 3.0
See also .getwd .home .for_fd .mkdir also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0