Ruby命令行解析

时间:2013-01-29 20:22:33

标签: ruby parsing command-line command-line-arguments

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

为什么@options在致电nil时会返回test()

我还尝试在首次调用Trollop时将@options设置为实例。我需要能够将Trollop返回的选项哈希传递给类中的不同方法。

4 个答案:

答案 0 :(得分:1)

如果您真的想要将类实例变量用于选项存储,那么这将起作用:

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

否则你可能想要使用类变量@@options或常量,就像其他指出的那样。

答案 1 :(得分:0)

这里有一个范围问题。类上下文中的@options是类的实例变量。在test中,您可以访问当前实例中的实例变量@options。尝试使用词法范围的常量,即OPTIONS。也许其他人知道更清洁的解决方案。

答案 2 :(得分:0)

正如Tass指出的那样,将@options更改为OPTIONS是一种方式。

您也可以在任一上下文中使用@@options;它是一个类变量。

答案 3 :(得分:0)

您正在添加一个类实例变量,但是当您在方法中引用它时,您将引用看起来像实例变量的内容。

首先,您可能希望改为使用类变量而不是类实例变量。有关区别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

另一个选项是在初始化测试对象时实例化您的类变量,如下所示:

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
相关问题