0

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.

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, that fixed it right away! All methods fully functional, thanks so much for your help! You're a lifesaver!
0

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

1 Comment

How would I define ip_histogram on Array, define it on the Array class? Inherit the Array class into the CommonLog class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.