开发者

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

开发者 https://www.devze.com 2022-12-14 11:33 出处:网络
I want to do something like assert_match /blah blah blah #{@user}/, @some_text but I\'m not having any luck with it working.

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 wron开发者_JS百科g here?


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


If there's any possibility of the @user string containing special regexp characters, you should modify this to:

/blah blah blah #{Regexp.escape(@user)}/


you can take a look at %r{}, for example:

pattern = 'foo'
%r{#{pattern}_bar} =~ 'foo_bar_2000'


assert_match also takes a string, like

assert_match("blah blah", 'a string')

so the other way to do what you are doing would be to user string interpolation

string_to_match = "blah blah #{@user}"

assert_match(string_to_match, 'a string')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号