Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby grep with string argument

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

Example:

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. Thanks.

like image 855
gkaykck Avatar asked May 10 '12 12:05

gkaykck


2 Answers

Regular expressions support interpolation, just like strings:

var = "hello"
re = /#{var}/i
p re #=> /hello/i
like image 200
steenslag Avatar answered Nov 04 '22 09:11

steenslag


Having something in quotes is not the same as the thing itself. /a/i is Regexp, "/a/i" is string. To construct a Regexp from string do this:

r = Regexp.new str
myArray.grep(r)
like image 5
Ivaylo Strandjev Avatar answered Nov 04 '22 10:11

Ivaylo Strandjev