user3784251 user3784251 - 2 months ago 9
Ruby Question

How to interpolate a regex into string and use that string as regex to compare in ruby

Consider i have a strings

goo = "test check\ncode"

if goo =~ /#{Regexp.quote(foo)}/
puts "success!"
end


I need to compare with "foo" regex. How can i write this regex?

Kindly help me in to find this!

Answer

I assume that foo contains a string, which represents the regexp. If so, you can initialize Regexp object from that string and perform your matching as follows:

foo = 'test.*check.*code'

goo =~ Regexp.new(foo, Regexp::MULTILINE)
Comments