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
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.
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).
=~ 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.
E.g. (? i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With