Forum: Ruby Routing code question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B29827838126aaaf080325b3f241e496?d=identicon&s=25 RailsToPerl (Guest)
on 2007-05-21 21:13
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.
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (Guest)
on 2007-05-21 21:52
(Received via mailing list)
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.
This topic is locked and can not be replied to.