所以我使用了一个很棒的trollop gem来做选项解析,但是我对它设置的变量的作用域有一个普遍的问题。
require 'trollop'
class MyClass
opts = Trollop::options do
opt :thing, "does something", default: "blah", type: String
end
def my_method
puts opts[:thing]
end
end但我得到了:
undefined local variable or method `opts' for #<MyClass:0x0000010203c840> (NameError)你知道我的瞄准镜哪里做错了吗?
发布于 2011-09-14 10:25:59
这里大约有六个选项:实例变量,类实例变量,类变量,类常量,全局变量,全局常量。使用哪一种取决于您的需求。
实例变量-每个MyClass实例都有自己的选项:
class MyClass
def initialize
@opts = ...
end
def my_method
puts @opts[:thing]
end
end类实例变量-可以重新赋值的类中的单个值:
class MyClass
@opts = ...
class << self
attr_accessor :opts
end
def my_method
puts self.class.opts[:thing]
end
end类变量-每个MyClass和所有子类共享相同的值(语法很方便,但很少是一个好主意):
class MyClass
@@opts = ...
def my_method
puts @@opts[:thing]
end
end类常量-可以改变但不能重新分配的单个对象。可从该类轻松访问,也可通过MyClass::OPTS从其他类访问
class MyClass
OPTS = ...
def my_method
puts OPTS[:thing]
end
end全局变量-您在整个应用程序中只能使用其中之一;通常全局变量是不明智的,但可能适合独立应用程序的选项:
$opts = ...
class MyClass
def my_method
puts $opts[:thing]
end
end全局常量-从许多类访问,不能设置为新值,但可能会发生变化:
OPTS = ...
class MyClass
def my_method
puts OPTS[:thing]
end
end发布于 2011-09-14 09:09:55
你不应该只使用实例变量吗?
require 'trollop'
class MyClass
def initialize
@opts = Trollop::options do
opt :thing, "does something", default: "blah", type: String
end
end
def my_method
puts @opts[:thing]
end
end发布于 2011-09-14 09:12:16
您正在将“opts”定义为类中的局部变量。实例方法(如my_method)将无法访问它。opts是否应该对整个类都是“全局的”?在这种情况下:
class MyClass
@@opts = Trollop::options...
def my_method
puts @@opts[:thing]
end
end或者类的每个实例都应该有一个唯一的实例?
class MyClass
def initialize
@opts = Trollop::options...
end
def my_method
puts @opts[:thing]
end
end这可能是一本不错的读物:http://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby
https://stackoverflow.com/questions/7410179
复制相似问题