Project

General

Profile

Feature #10123

Named capture groups don't set local vars when matched using ~

Added by josh.cheek (Josh Cheek) about 5 years ago. Updated 14 days ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:64304]

Description

Broken when using ~:

$ echo ' josh' | ruby -ne '~/(?<initial>\w)/ and puts initial'
-e:1:in `<main>': undefined local variable or method `initial' for main:Object (NameError)

Working when using =~ $_:

$ echo ' josh' | ruby -ne '/(?<initial>\w)/ =~ $_ and puts initial'
j

History

Updated by nobu (Nobuyoshi Nakada) about 5 years ago

  • Description updated (diff)

I'm not sure if this should be a bug or a new feature.

Updated by josh.cheek (Josh Cheek) almost 4 years ago

Josh Cheek wrote:

Broken when using ~:

$ echo ' josh' | ruby -ne '~/(?<initial>\w)/ and puts initial'
-e:1:in `<main>': undefined local variable or method `initial' for main:Object (NameError)

Working when using =~ $_:

$ echo ' josh' | ruby -ne '/(?<initial>\w)/ =~ $_ and puts initial'
j

Similarly, these do not set the local variable.

$ echo ' josh' | ruby -ne '/(?<initial>\w)/ !~ $_ or puts initial'
$ echo ' josh' | ruby -ne '$_[/(?<initial>\w)/] and puts initial'
$ echo ' josh' | ruby -ne 'puts initial if /(?<initial>\w)/'
$ echo ' josh' | ruby -ne 'if /(?<initial>\w)/ then puts initial end'

Updated by jeremyevans0 (Jeremy Evans) about 2 months ago

  • Backport deleted (2.0.0: UNKNOWN, 2.1: UNKNOWN)
  • ruby -v deleted (ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-darwin13.0])
  • Tracker changed from Bug to Feature

Looking at the documentation for Regexp#=~ as well as the Capture section of the Regexp class documentation, both of which describe assignment of named captures to local variables, it seems intentional that only the /(?<some>re)/ =~ string case sets local variables. Even the string =~ /(?<some>re)/ case does not set them. So I think this should be considered a feature request.

Updated by matz (Yukihiro Matsumoto) 14 days ago

  • Status changed from Open to Rejected

Implicit assignment from named capture is kind of confusing. Unless strongly persuaded, I am not going to enhance the feature.
Although we have no plan to remove the feature.

Matz.

Also available in: Atom PDF