Hi --

On Fri, 1 Aug 2003, Gawnsoft wrote:

> I've finally overcome my newbie embarrassment enough to post about
> actual code

Welcome, nuby!

>    aDictionary = Hash.new(0)
>
>    aFile.each_line { | eachLine | aDictionary[ /[0-9.]+/ ] =
> aDictionary[ /[0-9.]+/ ] + 1 if
> eachLine.include?("plastic_1.1_lite-UMLtool-fw.exe") }
>
> All well and good - and I was surprised how quickly I got my head
> round file handling, hashes and regular expressions, and delighted at
> the way I could use a regexp as the index of a hash.

Yes, you can use a regex as a key, but in your example, you're not
doing anything else with it :-)  You'd get the same results with:

   dict[/blah/] = dict[/blah/] + 1

or even:

   dict[/blah/] = dict["hello!"] + 1

since dict["hello"] is just serving the purpose of evaluating to zero.

If you just want the count of lines with plastic_1.1..., you could do:

  plastic_count = file.readlines.grep(/plastic_1.1.../).size

or, to save reading the whole file in at once:

  plastic_count = 0
  file.readlines.each do |line|
    plastic_count += 1 if /plastic_1.1.../.match(line)
  end

If you want to hash by IP address, you could do:

  regex = /([\d.]+).*plastic_1\. etc./
  dict = Hash.new(0)

  File.open("filename") do |fh|
    fh.each_line do |line|
      m = regex.match(line)
      dict[m[1]] += 1 if m
    end
  end

In this example, I'm using a MatchData object, m.  m[1] contains the
results of the first capture (the ([\d.]+)).  m will be nil if the line
doesn't match -- hence the "if m".

(You could do the same thing using the special variable $1, but I'm
going for the full OO effect here :-)


David

-- 
David Alan Black
home: dblack / superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav