Ruby 哈希表中的多个匹配项

Ruby 哈希表中的多个匹配项,ruby,parsing,duplicates,Ruby,Parsing,Duplicates,在coursera学习Ruby(2.5节)。 目的是在ruby简单解析器上编写,该解析器将计算apache日志中负责最多查询的IP主机 Apache日志: 87.99.82.183 - - [01/Feb/2018:18:50:06 +0000] "GET /favicon.ico HTTP/1.1" 404 504 "http://35.225.14.147/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36

在coursera学习Ruby(2.5节)。 目的是在ruby简单解析器上编写,该解析器将计算apache日志中负责最多查询的IP主机

Apache日志:

    87.99.82.183 - - [01/Feb/2018:18:50:06 +0000] "GET /favicon.ico HTTP/1.1" 404 504 "http://35.225.14.147/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36"
    87.99.82.183 - - [01/Feb/2018:18:50:52 +0000] "GET /secret.html HTTP/1.1" 404 505 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36"
Ruby代码:

    class ApacheLogAnalyzer

      def initialize
        @total_hits_by_ip = {}
      end

      def analyze(file_name)
        ip_regex = /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}/
        file = File.open(file_name , "r")
        file.each_line do |line|
          count_hits(ip_regex.match(line))
        end
      end

      def count_hits(ip)
        if ip
          if @total_hits_by_ip[ip]
            @total_hits_by_ip[ip] += 1
          else
            @total_hits_by_ip[ip] = 1
          end
        end
      end
结果如下:

      {#<MatchData "87.99.82.183">=>1, #<MatchData "87.99.82.183">=>1}
{#=>1,#=>1}

结果包含重复项(它应该包含一个值为2的键“87.99.82.183”)。问题出在哪里?

在您的案例中,结果包含重复项,因为哈希键是不同的对象,但具有相同的值。请看以下示例:

a = "hello world foo".match(/he/) # => #<MatchData "he">
b = "hello world bar".match(/he/) # => #<MatchData "he">
a == b # => false

谢谢你的评论。我发现使用方法来解决这个问题。 因此,改进后的代码如下所示:

 count_hits(ip_regex.match(line).to_s)

问题是什么?如果你能证明什么是必须的,什么是伴随着努力而来的,这将是很有帮助的-否则这个问题会引起混乱,并且没有得到有效的回答。
 count_hits(ip_regex.match(line).to_s)