On Sun, 27 Aug 2000, Dave Thomas wrote:

> Having said that, this isn't really an iterator issue: we're using gsub to
> to the matching and the block attached to it to accumulate the results.

Thanks for the help. By combining this message (some nice tricks in your
code!) with your article on object oriented regexps, I came up with this.

  #! /usr/local/bin/ruby
    		 
  a = File.new("a").read(nil)
  table = Hash.new

  pattern = /(new|table|end)/

  a.scan(pattern) {|i|
    table[i] ||= []   
    table[i] += $~.begin(0)
  }
     
  puts table.inspect

which produces the following result:

  {["new"]=>[33, 65, 82], ["table"]=>[52, 86, 122, 140, 172], ["end"]=>[92]}

It doesn't iterate through the regexps, but at least it does get called for
every regexp match so I can access the intermediate values.

First observation was that the first way I tried it:

  for i in a.scan(pattern)
    table[i] ||= []   
    table[i] += $~.begin(0)
  end

doesn't allow access to the intermediate regexp values, so there's a
difference between {} and for..end. I thought it was syntaxic sugar?

Second observation is that "nil + []" results in an error, instead of just
"[]" as expected. I had to borrow your nifty trick of doing "||= []" to make
sure there was an array, instead of being able to do

  a.scan(pattern) {|i|
    table[i] += [ $~.begin(0) ]
  }

Any reason why "nil + []" should result in an error, or could this be a
small touchup for the library?

I'm enjoying Ruby. Perl and Python didn't excite me enough for me to expend
the effort to learn them, but Ruby keeps me glued to the computer.

Thanks for the help. :)

--
  steve / deaf.org