Ruby variable inside regex code

I run the grep method to filter by pattern. This is sample code.

companies.grep /city/ 

However, ruby ​​does not allow me to enter area_code with a block inside the rails view. Instead, I have to hardcode it like this:

 companies.grep /miami/ 

Keep in mind that a city is a variable. For instance,

 city = miami 

However, it is being updated. Do you know with whom I can pass a variable before the grep method?

Also, I tried the company .grep / # {city} /, but it didn’t work

+6
source share
1 answer
 companies.grep /#{city}/ # or companies.grep Regexp.new(city) 

In the case of a simple alpha-numeric query, this should be enough; but it’s better to use them to avoid if you are not going to have regular expression operators. So the best version is:

 companies.grep /#{Regexp.escape city}/ # or companies.grep Regexp.new(Regexp.escape city) 
+18
source

Source: https://habr.com/ru/post/975050/


All Articles