[英]Ruby command line parsing
class Test
options = Trollop::options do
opt :mode, "Select script mode", :default => 0
opt :net, "Internal IP range", :type => :string
end
@options = options
def test
pp @options
end
end
Why does @options
return nil
when I call test()
? 为什么在我调用
test()
时@options
返回nil
?
I've also tried setting @options
to instance when Trollop is first called. 我还尝试过在首次调用Trollop时将
@options
设置为实例。 I need to be able to pass the options hash returned from Trollop into different methods in the class. 我需要能够将Trollop返回的选项哈希传递到类中的不同方法中。
If you really want to use a class instance variable for option storage then this would work: 如果您真的想使用类实例变量进行选项存储,则可以这样做:
class Test
@options = Trollop::options ...
class << self
attr_accessor :options
end
def test
pp Test.options
# or self.class.options
end
end
# And this will work too..
pp Test.options
Otherwise you might want to use a class variable @@options
or constant, like the other ones pointed out, instead. 否则,您可能想要使用其他变量指出的类变量
@@options
或常量。
What you have here is a scoping issue. 您在这里遇到的是一个范围界定问题。
@options
in class context is an instance variable of the class. 类上下文中的
@options
是类的实例变量。 In test
, you access the instance variable @options
in the current instance. 在
test
,您可以在当前实例中访问实例变量@options
。 Try constants, aka OPTIONS
, which have lexical scoping. 尝试具有词法作用域的常量,也称为
OPTIONS
。 Maybe someone else knows of a cleaner solution to this. 也许其他人知道更清洁的解决方案。
You're adding a class instance variable, but when you reference it in the method, you're referencing what looks like an instance variable. 您将添加一个类实例变量,但是当您在方法中引用它时,您将引用看起来像实例变量的对象。
First, you might want to instead use a class variable rather than a class instance variable. 首先,您可能想使用类变量而不是类实例变量。 There's some information on the distinction here .
这里有一些关于区别的信息 。
class Test
@@options = Trollop::options do
opt :mode, "Select script mode", :default => 0
opt :net, "Internal IP range", :type => :string
end
def test
pp @@options
end
end
Test.test
The other option is to instantiate your class variable when initializing the test object, as below: 另一个选择是在初始化测试对象时实例化类变量,如下所示:
class Test
def initialize
@options = Trollop::options do
opt :mode, "Select script mode", :default => 0
opt :net, "Internal IP range", :type => :string
end
end
def test
pp @options
end
end
t = Test.new
t.test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.