Keith Bennett Keith Bennett - 2 years ago 80
Ruby Question

How to get both hidden and nonhidden files in a single call

I have a directory with both hidden (name starting with

) and non-hidden files as follows:

$ ls -a1

How can I get a listing of all of them in a single call?

I expected
to return all files, but it doesn't:

# => ["not-hidden"]

The best I can think of is:

Dir['*'] + Dir['.*']
# => ["not-hidden", ".", "..", ".hidden"]

And I also expected there to be a way to use a regex, but I cannot find one, and it's not possible to use
because there is no call capable of getting both hidden and non-hidden from which to select.

Answer Source

You could use Dir::glob with the FNM_DOTMATCH flag:

Dir.glob('*', File::FNM_DOTMATCH)
#=> [".", "..", ".hidden", "not-hidden"]

or Dir::entries:

#=> [".", "..", ".hidden", "not-hidden"]

You can also combine patterns using {p,q}, so Dir['{*,.*}'] would also work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download