2017-03-22 24 views
-1

print_jsonというメソッドをlist_trendsという名前の別のメソッドに含まれている条件文の中で呼び出そうとしています。私はこのコードを使ってコードを入れすぎたように見え始めていました。Ruby:別のメソッドの条件文内でメソッドを呼び出す

syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '(' 
...i_key]) ? print_trends : puts "Invalid API Key, operation ab... 
ここ

が私のコードです:

#!/usr/bin/ruby 

require 'thor' 
require 'json' 

class ListTrends < Thor 
    desc "list trends", "list out trends from JSON file" 

    option :api_key, :aliases => "--api-key", :type => :string, :required => true 

    def print_json 
    json = File.read('trends_available.json') 
    trends_hash = JSON.parse(json) 

    trends_hash.each do |key| 
     key.each do |k,v| 
     puts "Trend #{k}: #{v}" 
     end 
     puts "" 
    end 
    end 

    def list_trends 
    re = /^(?=.*[a-zA-Z])(?=.*[0-9]).{8,}$/ 
    if options[:api_key] 
     if re.match(options[:api_key]) ? print_json : puts "Invalid API Key, operation abort..." 
    end 
    end 
end 

ListTrends.start(ARGV) 

答えて

3

この

if options[:api_key] 
    if re.match(options[:api_key]) ? print_json : puts "Invalid API Key, operation abort..." 
end 

がちょうど

if options[:api_key] 
    re.match(options[:api_key]) ? print_json : puts "Invalid API Key, operation abort..." 
end 

けれどもIであるべきしかし、私は言う、私は実行エラーが出ます以下を好むでしょう:

if options[:api_key] 
    if re.match(options[:api_key]) 
    print_json 
    else 
    puts "Invalid API Key, operation abort..." 
    end 
end 

それとも、1行の上に置く必要がある場合:

if options[:api_key] 
    if re.match(options[:api_key]) then print_json else puts "Invalid API Key, operation abort..." end 
end 
関連する問題