Reputation: 45
So I'm receiving the error message "undefined method 'ip_histogram' for # (NoMethodError)" with the following code
class CommonLog
def initialize(logfile)
@logfile = logfile
end
def readfile
@readfile = File.readlines(@logfile).map { |line|
line.split()
}
@readfile = @readfile.to_s.split(" ")
end
def ip_histogram
@ip_count = 0
@readfile.each_index { |index|
if (@readfile[index] =~ /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ )
puts @readfile[index]
puts @ip_count += 1
end
}
end
end
my_file = CommonLog.new("test_log")
cleaned_file = my_file.readfile
puts cleaned_file.ip_histogram
I'm trying to read the array in and check it with regex. It works if I take the code out of the method and just throw it into the main program, but I'd like to know why it doesn't work as a method.
Upvotes: 0
Views: 3501
Reputation: 15957
You're assigning the results of CommonLog#readfile
to a new variable cleaned_file
. You didn't supply any input but I'm going to assume @readfile is an array
at this point.
That means your code is going to assume there's an instance method ip_histogram
on the Array
class when in fact there is not.
You'll simply want to run these in sequence to get the result you're after:
clog = CommonLog.new("test_log")
clog.readfile
clog.ip_histogram
The primary difference here is that we're not using the return value of readfile
as it only needs to set the variable in the method for ip_histogram
to work.
Upvotes: 3
Reputation: 168081
The return value of my_file.readfile
is an array. Unless you defined ip_histogram
in Array
class, you cannot call it on cleaned_file
.
To define ip_histogram
on Array
(with different definition than in your code):
class Array
def ip_histogram
...
end
end
Upvotes: 0