Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put Ruby Variable inside of Regex Code

I'm running the grep method to filter by pattern matching. This is an example code.

companies.grep /city/

However, ruby isn't allowing me to input the area_code withing the block inside the rails view. Instead, I'm forced to hardcode it like so:

companies.grep /miami/

Keep in mind, city is a variable. For example,

city = miami

However, it updates. Do you know how can I pass a variable through the grep method?

Also, I tried companies.grep /#{city}/, but it didn't work

like image 776
user3465296 Avatar asked Sep 10 '14 03:09

user3465296


People also ask

Can I use variable inside regex?

If we try to pass a variable to the regex literal pattern it won't work. The right way of doing it is by using a regular expression constructor new RegExp() . In the above code, we have passed the removeStr variable as an argument to the new RegExp() constructor method.

How do you include in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What does =~ mean in Ruby regex?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

What does (? I do in regex?

E.g. (? i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode.


1 Answers

companies.grep /#{city}/
# or
companies.grep Regexp.new(city)

In case of simple alpha-numeric query, this should suffice; but it is better to get into practice of escaping those, if you don't intend to have regexp operators. Thus, better version:

companies.grep /#{Regexp.escape city}/
# or
companies.grep Regexp.new(Regexp.escape city)
like image 69
Amadan Avatar answered Oct 03 '22 20:10

Amadan