aerijman
aerijman

Reputation: 2782

Slop parsing command line arguments with multiple inputs per argument option in ruby

I am using Slop in ruby to parse the input arguments:

slop_opts = Slop.parse(ARGV.map(&:strip)) do |o|                                
  o.string '--test1', 'explain test1'                             
  o.string '--test2', 'explain test2'                                      
  o.on '--help' do                                                              
    puts o                                                                      
    exit                                                                        
  end                                                                           
end                                                                             
                                                                                
slop_opts.to_hash      

And I need that test2 could include several options: e.g.

ruby this_script.rb --test1 one_arg --test2 first_arg second_arg

One constraint that I have is that I need first_arg and second_arg to be 2 different inputs, so I can't just get them from splitting on , (or similar) an input string like first_arg,second_arg.

Thank you for your help!

Upvotes: 2

Views: 116

Answers (1)

Schwern
Schwern

Reputation: 165596

Make --test2 an Array argument. Set the delimiter to nil to disable splitting the input.

slop_opts = Slop.parse(ARGV.map(&:strip)) do |o|                                
  o.string '--test1', 'explain test1'                             
  o.array '--test2', 'explain test2', delimiter: nil                                  
  o.on '--help' do                                                              
    puts o                                                                      
    exit                                                                        
  end                                                                           
end  

Then each input gets its own --test2.

ruby this_script.rb --test1 one_arg --test2 first_arg --test2 second_arg

Upvotes: 3

Related Questions