[英]Ruby: calling method within another method's conditional statement
我試圖調用包含在另一個方法命名list_trends條件語句中的方法print_json。 我這樣做是因為我的代碼看起來太嵌套了。 但是我在運行時看到一條錯誤消息:
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)
這個
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
雖然我更喜歡:
if options[:api_key]
if re.match(options[:api_key])
print_json
else
puts "Invalid API Key, operation abort..."
end
end
或者,如果您必須將其放在一行上:
if options[:api_key]
if re.match(options[:api_key]) then print_json else puts "Invalid API Key, operation abort..." end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.