Skip to content

Scanning methods that don't use Regexp don't clear named capture groups #135

Closed

Description

@andrykonchin

I noticed strange behaviour - #named_captures may return capture groups and #[] returns nil instead of raising IndexError in the following scenario:

  1. call a scanning method with a Regexp (with named capture groups)
  2. call a scanning method without a Regexp pattern (#getch, #get_byte or #scan_until/#exist?/... with a String pattern)
  3. call #[] with a named capture group (used in the Regexp) and #named_captures

I would expect that #[] raises IndexError and #named_captures returns nil.

Example

require 'strscan'

s = StringScanner.new('Fri Dec 12 1975 14:39')

s.scan(/(?<wday>Fri)/)
p s.named_captures # => {"wday" => "Fri"}
p s["wday"] # => "Fri"

s.get_byte
p s.named_captures # => {"wday" => nil}
p s["wday"] # => nil

s["month"] # => undefined group name reference: month (IndexError)

Wondering whether it's correct behaviour.

Activity

  1. kou commented on Feb 13, 2025

    @kou
    Member

    Good catch!

    We should clear named captures.

  2. kou commented on Feb 20, 2025

    @kou
    Member

    @naitoh Do you want to work on this too?

  3. naitoh commented on Feb 20, 2025

    @naitoh
    Contributor

    Do you want to work on this too?

    Yes, I would like to try this issue, too.

  4. added 4 commits that reference this issue on Feb 22, 2025
    1b3de41
    2b814b2
    56368c2
    38ef27a
  5. added a commit that references this issue on Feb 23, 2025
    b957443
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions