Stephen White <steve / deaf.org> writes:

>   a.scan(pattern) {|i|
>     table[i] ||= []   
>     table[i] += $~.begin(0)
>   }
>      
>... 
> 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?

The difference is that

  for in in xxx

is (almost)  equivalent to

  xxx.each do {|i|

The difference between this and your first piece of code is the
'each': In your initial code, the block in invoked by the scan. In the 
second, you iterate over the array _returned_ by the scan.

(btw: scan is a far better way of doing this than my gsub example).

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

Sometimes, having it return an error helps you find more insidious
bugs in your code. However,it is an interesting idea. What general
impact would it have if

   nil + x  -> x

It would help with both the Hash stuff above, and also with things
like

   str.scan(/\w+/) { |w| freq[w] += 1 }


Matz: what obvious major flaw am I missing here?


Dave