Ruby: check for nil object

  def parse( line )
    _, remote_addr, status, request, size, referrer, http_user_agent, http_x_forwarded_for = /^([^\s]+) - (\d+) \"(.+)\" (\d+) \"(.*)\" \"([^\"]*)\" \"(.*)\"/.match(line).to_a

    print line
    print request
    if request && request != nil
      _, referrer_host, referrer_url = /^http[s]?:\/\/([^\/]+)(\/.*)/.match(referrer).to_a if referrer
      method, full_url, _ = request.split(' ')

in parse: private method 'split' called for nil:NilClass (NoMethodError)

So, I understand that it calls splitnot for the string, but for nil. This part analyzes the web server log. But I can’t understand why he gets it nil. As I understand it, this is null.

Some of the subpatterns in regex failed? So is this a web server error that sometimes generates invalid logging lines?

By the way, how to write to a file in ruby? I cannot read this cmd window correctly under the windows.

+3
source share
3 answers

You seem to have a few questions, so I'll take a hit on what seems to be the main one:

, - , .nil? - request.nil?, true, nil false .

+7

:

File.open("file.txt", "w") do |file|
  file.puts "whatever"
end

- , nil. , , referrer , , , . EDIT , nil. , .

rubular.com, . " " " " , "Match result".

, " "? Apache, .

+2

Ruby 2.3.0 adds a secure navigation operator ( &.), which checks nilbefore calling a method.

request&.split(' ')

It is more or less semantically equivalent.

!request.nil? && request.split(' ')
+2
source

All Articles