gkaykck gkaykck - 1 year ago 127
Ruby Question

Ruby grep with string argument

I want to use grep with a string as regex pattern. How can i do that?


myArray.grep(/asd/i) #Works perfectly.

But i want to prepare my statement first

searchString = '/asd/i'
myArray.grep(searchString) # Fails

How can i achieve this? I need a string prepared because this is going into a search algorithm and query is going to change on every request.

Answer Source

Regular expressions support interpolation, just like strings:

var = "hello"
re = /#{var}/i
p re #=> /hello/i
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download