Ruby: Use variable inside Regex

While coding into Ruby, sometime you may need to use some variable inside the regular expression. For example you have a string, and you need to match the string with some value of a variable.

Here is how it has to be done. Inside the regex, you just need to use the value inside two second brackets and a hash(#) sign left side. I mean #{your_variable} which is similar when you print a value inside double quote("").

For example, you have a string, and a variable. you are checking whether the variable's value is inside the string or not.
string = "ten = 10 and 10 has one 0 and one 1";
variable = 10;

## Check whether the value of the variable
## is inside the string or not.
if(string =~ /#{variable}/)
print "#{variable} has inside the string\n";
end

It will output '10 has inside the string'

You can use the match() function to match the regex. to use match
## Another approach
if( /#{variable}/.match(string) )
print "Again #{variable} has inside the string\n";
end


This things also works with the gsub() function to replace string using pattern. I'm replacing all 10s into 11s using gsub() function of ruby.
## replacing using variable
replace = '11';
string = string.gsub(/#{variable}/, replace);
print "#{string}\n";


Thats all. you can read few other ruby articles from my blog, and here it is http://icfun.blogspot.com/search/label/ruby

Comments

Anonymous said…
This was very helpful - The gsub part in particular. Thanks!
John Rodkey said…
When I use this syntax,
string.gsub!(/#{variable}/,replace);
I get a syntax error because ruby sees the # as the beginning of a comment, and thus the closing paren of the gsub! doesn't get seen.

Any hints?

John
Tom said…
I know this is an old article but I just found this useful 4 years after it was posted. Thanks ! :)