Better way to get a list of files in a given directory

Viewed 37

When I need to work with files in a given directory, I always resort to the following way, which to my opinion is cumbersome:

    this_dir = Dir.pwd
    filepath = File.join(this_dir, "directory")
    file_list = Dir[File.join(filepath, "*.txt")]

I know that the code below returns an array of filenames. Supposedly there is only one file in that directory, the way I'm used to reaching to is:

    File.basename(file_list[0])

Are there better and tidier ways to get a list of files in a directory, so that I can do whatever I want with these?

1 Answers

There's some things to note here. In many cases file operations are presumed to work based on your current working directory, Dir.pwd, so that does not need to be specified.

The easiest way to find the first matching file is:

Dir['directory/*.txt'].first

There's not much to be gained here over your file_list approach, except that you don't need all the preamble.

Related