Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - How do you insert a variable into a regular expression (Regex) for instance assert_match

Tags:

I want to do something like

assert_match /blah blah blah #{@user}/, @some_text 

but I'm not having any luck with it working.

What am I doing wrong here?

like image 745
robodisco Avatar asked Dec 17 '09 12:12

robodisco


People also ask

Can you add variables to regex?

There is the regex constructor which takes a string, so you can build your regex string which includes variables and then pass it to the Regex cosntructor.

What does =~ mean in Ruby regex?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.

What kind of regex does Ruby use?

A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.


1 Answers

That is the correct way to insert a variable into a regex:

irb(main):001:0> a='Hi' => "Hi" irb(main):002:0> b=/Not #{a}/ => /Not Hi/ 

So your problem is likely that the assert is failing because of a bad match. Check the value of @user and @some_text and try http://rubular.com to come up with a matching regexp

like image 194
Drew Blas Avatar answered Oct 26 '22 14:10

Drew Blas