2

I'm trying to use the regex global variable with the ruby gsub! method.

What I have in mind is something like this:

MyTextString.gsub!(/regex expression/,$1)

This is how I've approached it but its not working. Is this possible or perhaps my regex isn't working.

1
  • 1
    You'd use $1 with the block form of gsub. Commented Aug 8, 2012 at 2:24

1 Answer 1

9

Use '\1' instead of $1 ($1 references a variable which doesn't exist yet, since you haven't matched the regex yet)

Also, "my regexp isn't working" makes it difficult to help. A better phrase would be one which explains why it isn't working (string is same afterwards, or an error is raised, or whatever), and provides the data (string and regex) necessary to reproduce the problem.

str = "abcdefg"
str.gsub!(/a(.)c/, '\1')
str # => "bdefg"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Point taken on my question, appreciate the feedback. With regard to the $1, I assume the match doesn't take place until the whole gsub command is completed. Thanks again.
It's not that "the match doesn't take place until the whole command is completed". When a method is called, the arguments to a method are evaluated before the method executes. So if you do /regexp/.gsub("str",$1), first Ruby will evaluate "str" and $1, then it executes gsub. $1 is a global variable which is set by the Ruby interpreter after a regexp matches. So if you just did a regexp match (on a preceding line), $1 will be set, and the value of that (previous) match will become the 2nd argument to gsub.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.