Project

General

Profile

Actions

Feature #10123

closed

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

Added by josh.cheek (Josh Cheek) over 10 years ago. Updated about 5 years ago.

Status:
Rejected
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

Updated by nobu (Nobuyoshi Nakada) about 10 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) about 9 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) over 5 years ago

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

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) about 5 years 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.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0