# Routing code question

**URL:** <https://www.ruby-forum.com/t/routing-code-question/104721>\
**Category:** Ruby\
**Created:** [May 21, 2007, 9:13pm UTC](https://www.ruby-forum.com/t/routing-code-question/104721 "2007-05-21T21:13:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![RailsToPerl](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a5b964/32.png) [@RailsToPerl](https://www.ruby-forum.com/u/RailsToPerl)\
**Post date:** [May 21, 2007, 9:13pm UTC](https://www.ruby-forum.com/t/routing-code-question/104721/1 "2007-05-21T21:13:30Z")

</div>

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? It’s always going to match ‘’  
with the blank spot before the | and therefore will have no captures.

---

<div class="post-metadata">

**Author:** ![RailsToPerl](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a5b964/32.png) [@RailsToPerl](https://www.ruby-forum.com/u/RailsToPerl)\
**Post date:** [May 21, 2007, 9:52pm UTC](https://www.ruby-forum.com/t/routing-code-question/104721/2 "2007-05-21T21:52:00Z")

</div>

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.
