簡體   English   中英

Ruby命令行解析

[英]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

為什么在我調用test()@options返回nil

我還嘗試過在首次調用Trollop時將@options設置為實例。 我需要能夠將Trollop返回的選項哈希傳遞到類中的不同方法中。

如果您真的想使用類實例變量進行選項存儲,則可以這樣做:

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或常量。

您在這里遇到的是一個范圍界定問題。 類上下文中的@options是類的實例變量。 test ,您可以在當前實例中訪問實例變量@options 嘗試具有詞法作用域的常量,也稱為OPTIONS 也許其他人知道更清潔的解決方案。

正如Tass指出的那樣,將@options更改為OPTIONS是一種方法。

您也可以使用@@options; 無論哪種情況,它都是一個類變量。

您將添加一個類實例變量,但是當您在方法中引用它時,您將引用看起來像實例變量的對象。

首先,您可能想使用類變量而不是類實例變量。 這里有一些關於區別的信息

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM