2017-03-27 11 views
0

なしトールコマンドを実行します。Rubyは - 私は、スクリプトを実行するには、このコマンドを使用する必要があり、引数

$ruby file.rb keyword --format oneline --no-country-code --api-key=API

formatno-country-codeapi-keythorオプションです。 keywordは私のメソッドで引数です:

class TwitterTrendReader < Thor 
    method_option :'api-key', :required => true 
    method_option :format 
    method_option :'no-country-code', :type => :boolean 

    def execute (keyword) 
     #read file then display the results matching `keyword` 
    end 

default_task :execute 
end 

問題はkeywordは、私はkeywordせずにコマンドを実行した場合、スクリプトはそれ以外の場合は、ファイル内のすべてのエントリを印刷する必要があり、オプションであり、それが唯一のエントリを表示しますkeywordと一致します。

ので、私はこのコードを持っている:

if ARGV.empty? 
    TwitterTrendReader.start '' 
else 
    TwitterTrendReader.start ARGV 
end 

それは唯一私がkeywordを指定するときに動作しますがkeywordせずに、私はこれを取得:

$ruby s3493188_p3.rb --api-key="abC9hsk9" 
ERROR: "s3493188_p3.rb execute" was called with no arguments 
Usage: "s3493188_p3.rb [keyword] --format oneline --no-country-code --api-key=API-KEY" 

は、だから、適切な方法は何を教えてください私は議論を任意にすることができました。ありがとうございました! def execute (keyword)

答えて

1

あなたの現在の実装では、(それが1つの必須パラメータを宣言し、言った。)アリティ1であるあなたがそれを省略する能力を持っているしたい場合は、パラメータはオプションにします。

変更

def execute (keyword) 
    #read file then display the results matching `keyword` 
end 

へ:

def execute (keyword = nil) 
    if keyword.nil? 
    # NO KEYWORD PASSED 
    else 
    # NORMAL PROCESSING 
    end 
end 
+0

それは非常に機能します。どうもありがとうございます! –

関連する問題