Reputation: 2193
just a newbie to Ruby here:
Tried similar code today as below:
m = /(.*)xyz(.*)/.match("abcxyzdef")
subsequently ruby will set global variables $1 = “abc" and $2 = “def" but if code is like
str1 = $1
str1.gsub!('a', '0')
str2 = $2
in this case, str2 will NOT be able to get value from match groups str2=nil
, unless
str1 = $1
str2 = $2
str1.gsub!('a', '0')
so just curious what magic is behind this?
Thanks for your help!
Upvotes: 0
Views: 134
Reputation: 54734
As @UriAgassi suggested, I would prefer to access the MatchData object returned by match
because it is less cryptic than the $0
, …, $9
global variables. However, I tend to like the block form of match
better, because it makes it clear what regex the matches belong to.
/(.*)xyz(.*)/.match("abcxyzdef") do |m|
str1, str2 = m.captures
str1.gsub!('a', '0')
end
Upvotes: 0
Reputation: 37419
Of course, you can always use the match return value (you even assign it to m
):
str1 = m[1]
# => "abc"
str1.gsub!('a', '0')
# => "0bc"
str2 = m[2]
# => "def"
Upvotes: 0
Reputation: 10806
gsub
, like match
uses the regex engine and thus overwrites the $1, $2 variables. If you want access to the data stored in those variables, you need to store them in a temporary variable before excecuting another regex method.
result = [$1, $2]
Upvotes: 4