Keith Bennett Keith Bennett - 7 months ago 8
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
.
..
.hidden
not-hidden


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

I expected
Dir['*']
to return all files, but it doesn't:

Dir['*']
# => ["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
select
and
grep
because there is no call capable of getting both hidden and non-hidden from which to select.

Answer

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

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

or Dir::entries:

Dir.entries('.')
#=> [".", "..", ".hidden", "not-hidden"]

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

Comments