Search code examples
rubyoptionparser

Nil parameter in OptionParser


i try to set my script to run something like this

ruby Script.rb --ip "192.168.3.206"

But if there is no ip parameter then it use default "192.168.1.1

I try this code, but it's always return nil as ip

options = {}

OptionParser.new do |opts|
  options[:ip] = "192.168.1.1"
  opts.on("-i", "--ip", String, "Set ip") do |command_line_ip|
    options[:ip] = command_line_ip
  end
end.parse!
p options

Output of this code is

{:ip=>nil}

Please, tell me where is my code wrong?


Solution

  • You have to indicate that there is an argument to your --ip switch like this:

    opts.on("-i MANDATORY", "--ip=MANDATORY", String, "Set ip") do |command_line_ip|