Search code examples
rubydefault-valueoptparse

How to default to information if none is given using optparse


I have a program that creates emails, what I want to do is when the -t flag is given and no argument is given with the flag, default to something, instead it outputs the usual: <main>': missing argument: -t (OptionParser::MissingArgument)

So my question being, if I have this flag:

require 'optparse'

OPTIONS = {}

OptionParser.new do |opts|
  opts.on('-t INPUT', '--type INPUT', 'Specify who to say hello to'){ |o| OPTIONS[:type] = o }
end.parse!

def say_hello
  puts "Hello #{OPTIONS[:type]}"
end  

case
  when OPTIONS[:type]
    say_hello
  else
    puts "Hello World"
end   

and I run this flag without the required argument INPUThow do I get the program to out put the Hello World instead of the: <main>': missing argument: -t (OptionParser::MissingArgument)?

Examples:

C:\Users\bin\ruby\test_folder>ruby opt.rb -t hello
Hello hello

C:\Users\bin\ruby\test_folder>ruby opt.rb -t
opt.rb:7:in `<main>': missing argument: -t (OptionParser::MissingArgument)

C:\Users\bin\ruby\test_folder>

Solution

  • I figured out that by adding brackets around the INPUT I can provide the option to provide input examples:

    require 'optparse'
    
    OPTIONS = {}
    
    OptionParser.new do |opts|
      opts.on('-t [INPUT]', '--type [INPUT]', 'Specify the type of email to be generated'){ |o| OPTIONS[:type] = o }
    end.parse!
    
    def say_hello
      puts "Hello #{OPTIONS[:type]}"
    end  
    
    case 
      when OPTIONS[:type]
        say_hello
      else
        puts "Hello World"
    end
    

    Output:

    C:\Users\bin\ruby\test_folder>ruby opt.rb -t
    Hello World
    
    C:\Users\bin\ruby\test_folder>ruby opt.rb -t hello
    Hello hello
    

    So if I do this:

    require 'optparse'
    
    OPTIONS = {}
    
    OptionParser.new do |opts|
      opts.on('-t [INPUT]', '--type [INPUT]', 'Specify the type of email to be generated'){ |o| OPTIONS[:type] = o }
    end.parse!
    
    def say_hello
      puts "Hello #{OPTIONS[:type]}"
      puts
      puts OPTIONS[:type]
    end  
    
    case 
      when OPTIONS[:type]
        say_hello
      else
        puts "Hello World"
        puts OPTIONS[:type] unless nil; puts "No value given"
    end
    

    I can output the information provided, or when there's no information provided I can output No value given:

    C:\Users\bin\ruby\test_folder>ruby opt.rb -t hello
    Hello hello
    
    hello
    
    C:\Users\bin\ruby\test_folder>ruby opt.rb -t
    Hello World
    
    No value given