Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here's a sample code using the 'slop' gem to obtain an array of filenames after a shell glob:

require 'slop'

opts = Slop.parse do |o|
  o.string '-p', '--path', 'Path to search for files', required: true
  o.string '-e', '--extension', 'File extension to search for', default: '*'
  o.bool '-i', '--ignore-case', 'Ignore case while searching', default: false
end

path = opts[:path]
extension = opts[:extension]
ignore_case = opts[:ignore_case]

# Build the glob pattern based on user inputs
glob_pattern = File.join(path, "**", "*.#{extension}")

# Search for files that match the glob pattern
filenames = Dir.glob(glob_pattern)

# Filter results based on case sensitivity
unless ignore_case
  filenames = filenames.select do |filename|
    File.basename(filename) == File.basename(filename).downcase
  end
end

# Print the list of files (if any)
if filenames.empty?
  puts "No files found with the specified criteria"
else
  puts "List of files found:"
  filenames.each { |filename| puts filename }
end

In this example code, we are using 'Slop' to define command-line options for the user to specify the path, file extension, and whether or not to ignore case while searching for files.

We then build a glob pattern based on the user inputs (using File.join and ** to search recursively through subdirectories). We use the Dir.glob method to search for files that match the glob pattern, which returns an array of filenames.

We then optionally filter the results based on case sensitivity using the select method of the Array class. Finally, we print the list of files found (if any) using puts.