Project

General

Profile

Actions

Feature #18291

open

When use =~ with named group, if regex is on the right side, variable not defined.

Added by zw963 (Wei Zheng) 11 months ago. Updated 11 months ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:105947]

Description

Following code not work.

if "Billy Zheng" =~ /(?<first_name>\w+)\s+(?<last_name>\w+)/
  p first_name
  p last_name
end
# NameError: undefined local variable or method `first_name' for main:Object

But, if we switch left and right between =~

if /(?<first_name>\w+)\s+(?<last_name>\w+)/ =~ "Billy Zheng"
  p first_name
  p last_name
end
# => "Billy"
# =>"Zheng"

I know ruby keep this same behavior since 1.9, but i am curious if we can improve this?

I consider this as a bug, because that not good, when i want to use this way, i have to
take care must write regexp before =~

Thank you.

Updated by jeremyevans0 (Jeremy Evans) 11 months ago

  • Tracker changed from Bug to Feature
  • Backport deleted (2.6: UNKNOWN, 2.7: UNKNOWN, 3.0: UNKNOWN)

regexp.rdoc documents that the literal regexp must be on the left hand side in order to assign to local variables, so this is not a bug. Switching to feature request.

Updated by zw963 (Wei Zheng) 11 months ago

jeremyevans0 (Jeremy Evans) wrote in #note-1:

regexp.rdoc documents that the literal regexp must be on the left hand side in order to assign to local variables, so this is not a bug. Switching to feature request.

Hi, Jeremy, thank you for answer, yes, maybe it is a feature, not a bug, but, i guess do some trick specially only for this named regexp group matching to make variable is always available maybe is possible.

Actions

Also available in: Atom PDF