0

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
Community
  • 1
  • 1
Jasmine Lognnes
  • 6,597
  • 9
  • 38
  • 58
  • 3
    You're telling ruby to output the value of `username` via the `puts username`, but `username` isn't defined. – lurker Apr 14 '17 at 15:51

2 Answers2

2

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.

mikej
  • 65,295
  • 17
  • 152
  • 131
1

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]
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160