[Ilugc] Help needed in ruby

  • From: ranjith.k@xxxxxxxxxxx (Ranjith)
  • Date: Thu Sep 2 16:45:57 2010

Hi all,
     When I run the script I got this error message.

        undefined method `[]' for nil:NilClass (NoMethodError)
from chandra.rb:11:in `collect'
 from chandra.rb:11

# --------------8<---------------------------------8<---------------

require 'rubygems'
require 'apachelogregex'
require 'pp'

format = '%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"'
parser = ApacheLogRegex.new(format)
access_log = Hash.new
# Creating a hash of an array of hashes!
# Can be simplified based on your actual requirement.

File.readlines('aleurier_access.log').collect do |line|

 record = parser.parse(line)
 # The code below does the actual job. Can be a one-liner
 # if you know ternary operators or maybe if expression.
 if access_log.key? record["%h"]
    access_log[record["%h"]] << record
 else
    access_log[record["%h"]] = Array.new
 end
end

# Now let's test some!
puts access_log.keys
while true
   print "Enter ip address: "
   ipaddr = gets.chomp
   puts "-" * 40
   pp access_log[ipaddr]
   puts "-" * 40
end
# --------------8<---------------------------------8<---------------

Is this what you wanted ?

yes exactly this is what I want to do.

I tried this way it runs fine


require 'rubygems'
require 'apachelogregex'
require 'set'
require 'pp'

urls = Set.new
format = '%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}\"'
  parser = ApacheLogRegex.new(format)
  File.readlines('aleurier_access.log').collect do |line|
  l = parser.parse(line)
   urls.add(l["%r"])
      # {"%r"=>"GET /blog/index.xml HTTP/1.1", "%h"=>"87.18.183.252", ... }
end
puts urls.to_a.sort
pp l

but I still get an error.
undefined local variable or method `l' for main:Object (NameError)
 I tried using @l but no use

Thanks alot

-- 
Cheers,
Ranjith Kumar.K,
Software Engineer,
Sedin Technologies,

http://ranjithtenz.wordpress.com/
http://victusads.com/

Other related posts: