All of the other similar regexp variables ($& $' $+ $~ $(backquote)
) are listed by global_variables
, so it would make sense for $1
and similar to appear, or alternatively for the other 5 regexp globals not to appear if there is no match. If there is no backref, the other 5 regexp globals still appear. If there is a backref, and it has no captures, it doesn't make sense for $+
to be included and $1
not to be included.
I'm not sure whether $1
through $9
should be present for consistency, even the last match did not have that number of captures. I think that would be more consistent to include all of them if we are including $+
in the case of no matches. However, that would make global_variables
less consistent with defined?
.
Related to this, defined?
is a little strange for the regexp globals:
puts %w[$~ $& $` $' $+ $1 $2].map{|s| "#{s}: #{eval("defined?(#{s})").inspect}"}
# $~: "global-variable"
# $&: nil
# $`: nil
# $': nil
# $+: nil
# $1: nil
# $2: nil
/(.)/ =~ "a"
puts %w[$~ $& $` $' $+ $1 $2].map{|s| "#{s}: #{eval("defined?(#{s})").inspect}"}
# $~: "global-variable"
# $&: "global-variable"
# $`: "global-variable"
# $': "global-variable"
# $+: "global-variable"
# $1: "global-variable"
# $2: nil
I would assume that defined?($~)
should be nil if the others are nil. Alternatively, it would make sense for defined?
to always return global-variable
for $& $' $~ $(backquote)
. $!
is similar to the regexp globals in terms of scoping, and it returns global-variable
even if not set.
I checked and defined?($+)
is nil
if the backref has no captures. I don't think we can change the behavior of defined?($+)
or defined?($1)
without significantly breaking backwards compatibility.
Also kind of weird is that defined?
treats aliases of these global variables differently than it treats the variables themselves:
defined?($&) # nil
alias $MATCH $&
defined?($&) # nil
defined?($MATCH) # "global-variable"
I would think we would want defined?
to treat global variable aliases the same as the global variables they alias.