使用args Ruby脚本解决变量范围问题

时间:2015-06-09 00:14:21

标签: ruby args

在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

1 个答案:

答案 0 :(得分:2)

你应该以你声明的方式引用全局变量,我的意思是你应该在前面添加'$':

<__main__.ObjName object at 0xxxxxx>

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