Reputation: 7127
Based on this answer have I the below code which gives
undefined local variable or method `username' for main:Object (NameError)
Question
I assume this worked in 2014, so can anyone see why this doesn't work on a modern version of Ruby?
#!/usr/bin/ruby
USAGE = <<ENDUSAGE
Usage:
rejse_dumper [-h] [-v] [-u username] [-p password] [-a address]
ENDUSAGE
HELP = <<ENDHELP
-h, --help Show this help.
-u, --username The login username.
-p, --password Force create over an existing directory,
-a, --address The URL [Defaults to 'https://example.com']
ENDHELP
ARGS = { address: 'https://example.com' } # Setting default values
ARGV.each do |arg|
case arg
when '-h','--help' then ARGS[:help] = true
when '-u','--username' then next_arg = :username
when '-p','--password' then next_arg = :password
when '-a','--address' then next_arg = :address
else
if next_arg
ARGS[next_arg] = arg
end
end
end
if ARGS[:help]
puts USAGE
puts HELP if ARGS[:help]
exit
end
puts username
puts password
puts address
Upvotes: 0
Views: 68
Reputation: 66343
The code puts the command line arguments into a hash in this part:
if next_arg
ARGS[next_arg] = arg
end
but doesn't set up individual variables such as username
, password
etc. hence the error you're seeing.
so you can refer to the arguments like this:
ARGS[:username]
or assign them to individual variables:
username = ARGS[:username]
etc.
Upvotes: 2
Reputation: 121010
No, your assumption is incorrect.
To make it working, change:
puts username
puts password
puts address
to:
puts ARGS[:username]
puts ARGS[:password]
puts ARGS[:address]
Upvotes: 1