On Tue, May 22, 2007 at 04:13:31AM +0900, RailsToPerl wrote:
> In routing.rb, what is the purpose of the following piece of code:
> 
> class Regexp #:nodoc:
>   def number_of_captures
>     Regexp.new("|#{source}").match('').captures.length
>   end
> 
> 
> Does this method not always return 0?

Empirically, no it doesn't:

$ cat x.rb
class Regexp #:nodoc:
  def number_of_captures
    Regexp.new("|#{source}").match('').captures.length
  end
end

a = /(foo|bar|(baz))/
puts a.number_of_captures
$ ruby x.rb
2
$

I think the reason is that all captures are assigned. If they don't actually
capture anything then they are set to nil.

irb(main):001:0> /(abc)(def)?/.match("abc").captures
=> ["abc", nil]

Otherwise it would be confusing as you might not be able to work out what
had actually been considered. Consider:

irb(main):002:0> /(abc)?(def)(ghi)?/.match("def").captures
=> [nil, "def", nil]

You want the middle capture to be assigned to $2, not $1.

Regards,

Brian.