Ask Your Question
3

What is the process to obtain an array of filenames after a shell glob using the ruby gem 'slop'?

asked 2023-01-01 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-02-06 09:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-01 11:00:00 +0000

Seen: 8 times

Last updated: Feb 06 '23