find the contents of a directory in ruby

In Ruby, the Dir class provides a way to interact with directories. To list the contents of a directory, you can use the Dir.entries method. Here's an example:

main.rb
dir_path = "/path/to/directory"

# List all files and directories in the directory
Dir.entries(dir_path) #=> [".", "..", "file1.txt", "file2.txt", "subdir1", "subdir2"]

# List only files in the directory
Dir.entries(dir_path).select { |file| File.file?(File.join(dir_path, file)) } #=> ["file1.txt", "file2.txt"]

# List only directories in the directory
Dir.entries(dir_path).select { |file| File.directory?(File.join(dir_path, file)) } #=> ["subdir1", "subdir2"]

467 chars
12 lines

In the above example, Dir.entries returns an array of all files and directories in the specified directory. By selecting only the files or directories using the File.file? and File.directory? methods, you can filter the results as needed.

gistlibby LogSnag