处理文件路径参数:没有将nil隐式转换为String



我正在编写一个简短的ruby脚本,该脚本将一个文件作为参数,然后解析该文件。我在initialize方法中设置了一些条件,以确保文件路径存在并且可读,如果不存在,则会向用户打印错误消息。

然而,当我在没有文件的情况下运行该文件时;请添加日志文件路径";。我还收到以下错误消息。

please add log file path
Traceback (most recent call last):
3: from webserver_log_parser.rb:41:in `<main>'
2: from webserver_log_parser.rb:41:in `new'
1: from webserver_log_parser.rb:6:in `initialize'
webserver_log_parser.rb:6:in `exist?': no implicit conversion of nil into String (TypeError)

如果有人能解释为什么会发生这种情况以及解决这个问题的方法,我将不胜感激。

def initialize(log_file_path = nil)
puts 'please add log file path' unless log_file_path
puts 'Could not find the file path' unless File.exist?(log_file_path)
puts '${log_file_path} is unreadable' unless File.readable?(log_file_path)
extract_log_file(log_file_path)
end
def extract_log_file(log_file_path)
webpages = Hash.new { |url, ip_address| url[ip_address] = [] }
File.readlines(log_file_path).each do |line|
url, ip_address = line.split
webpages[url] << ip_address
end
sort_results(webpages)
end
def sort_results(results)
total_views = {}
unique_views = {}
results.each do |url, ip_address|
total_views[url] = ip_address.length
unique_views[url] = ip_address.uniq.length
end
display_results(total_views, unique_views)
end
def display_results(views, unique_views)
puts 'The most viewed pages are as follows:'
total_views_sorted = views.sort_by { |_k, count| -count }
total_views_sorted.each { |key, count| puts "#{key} #{count}" }
puts 'The pages with the most unique views are as follows:'
unique_sort = unique_views.sort_by { |_k, count| -count }
unique_sort.each { |key, count| puts "#{key} #{count}" }
end
end
if $PROGRAM_NAME == __FILE__
LogParser.new(ARGV[0])
end```

如果您想直接用消息终止脚本,可以使用abort

def initialize(log_file_path = nil) 
abort("please add log file path") unless log_file_path
abort("Could not find the file path") unless File.exist?(log_file_path)
abort("${log_file_path} is unreadable") unless File.readable?(log_file_path)
extract_log_file(log_file_path)
end

当您的保护条件被触发时,您需要停止进一步的处理(如果您已经确定file_path为零,则无需在file_path检查文件的可读性(。它可能看起来像这样,例如:

def initialize(log_file_path = nil)
unless log_file_path
puts 'please add log file path' 
return
end
unless File.exist?(log_file_path)
puts 'Could not find the file path' 
return
end
unless File.readable?(log_file_path)
puts '${log_file_path} is unreadable' 
return
end
extract_log_file(log_file_path)
end

最新更新