8

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

1 Answer 1

23
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)
Sign up to request clarification or add additional context in comments.

2 Comments

Those two are equivalent. There is zero chance for /#{city}/ to fail and Regexp.new(city) to succeed, given same city (unless someone went and redefined Regexp to mess with you).
However, it did in the rails view while Regexp.new(city) succeeded

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.