args Ruby 脚本的变量范围问题

Trouble with variable scope with args Ruby script

我在 Ruby 中将 args 读入全局变量时遇到变量范围问题。当我 运行 以下脚本时出现此错误。不确定我做错了什么;有什么想法吗?

$ ./parse_args_example.rb --config=./config/tests.yml --type=Mag --envs=['warm','humid']
ARGV =>
Creating new instance of FlashLight...
./parse_args_example.rb:45:in `<main>': undefined local variable or method `configArg' for main:Object (NameError)

代码:

#!/usr/bin/env ruby
$stderr.sync = true

require 'optparse'

# default options
$configArg  = "./config/config.yml"
$typeArg = "Mag"
$envsArg = ['dark','snow']
$ledArg = false

# parse arguments
ARGV.options do |opts|
  opts.on("--config=val", String)          { |val| configArg = val }
  opts.on("--type=val", String)            { |val| typeArg = val }
  opts.on("--envs=['rain','dusk']", Array) { |val| envsArg = val }
  opts.on("-l", "--led")                   { ledArg = true }
  opts.parse!
end

print "ARGV => ", ARGV.join(', '), "\n"

# class that runs tests
class FlashLight

  def initialize(config, type, envs, led)  
    # Instance variables  
    @config = config  
    @type = type
    @envs = envs
    @led = led
  end  

  def runTests
    puts "Running tests..."
    warn "config:   #{config.inspect}"
    warn "type:      #{type.inspect}"
    warn "envs:     #{envs.inspect.to_s}"
    warn "led:  #{led.inspect}"
  end

end

puts 'Creating new instance of FlashLight...'
flashlight = FlashLight.new(configArg, typeArg, envsArg, ledArg) 
flashlight.runTests

你应该像声明它一样引用全局变量,我的意思是你应该在它前面加上 '$' :

#!/usr/bin/env ruby
$stderr.sync = true

require 'optparse'

# default options
$configArg  = "./config/config.yml"
$typeArg = "Mag"
$envsArg = ['dark','snow']
$ledArg = false

# CHANGE HERE ! User global variables, not local variables.
# parse arguments
ARGV.options do |opts|
  opts.on("--config=val", String)          { |val| $configArg = val }
  opts.on("--type=val", String)            { |val| $typeArg = val }
  opts.on("--envs=['rain','dusk']", Array) { |val| $envsArg = val }
  opts.on("-l", "--led")                   { $ledArg = true }
  opts.parse!
end

print "ARGV => ", ARGV.join(', '), "\n"

# class that runs tests
class FlashLight

  def initialize(config, type, envs, led)  
    # Instance variables  
    @config = config  
    @type = type
    @envs = envs
    @led = led
  end  

  # CHANGE HERE ! You should use instance variables here, not local variables.
  def runTests
    puts "Running tests..."
    warn "config:   #{@config.inspect}"
    warn "type:      #{@type.inspect}"
    warn "envs:     #{@envs.inspect.to_s}"
    warn "led:  #{@led.inspect}"
  end

end

puts 'Creating new instance of FlashLight...'
# CHANGE HERE ! Use global variables.
flashlight = FlashLight.new($configArg, $typeArg, $envsArg, $ledArg) 
flashlight.runTests 

否则它们只是普通的局部变量。有关变量的更多信息:Ruby Variables, Constants and Literals.