1

I am using Ruby 1.9.2p320 and running the following code snippet:

a = ["abc", "def", "pqr", "xyz"]
z = ["abc", "xyz"]
a.grep(/#{z}/)

That gives this output: ["abc", "xyz"].

a = ["abc_1", "def_1", "pqr_1", "xyz_1"]
z = ["abc_1", "xyz_1"]
a.grep(/#{z}/)

But this gives output as: ["abc_1", "def_1", "pqr_1", "xyz_1"].

What I expected was just ["abc_1", "xyz_1"].

Any particular reason why am i getting that output? And how could I get the expected output?

1
  • I tested with Ruby version 2.0.0p247. Same result. Not sure why it is happening. Commented Dec 3, 2013 at 9:04

3 Answers 3

5

You are building the regexp the wrong way, you should do something like:

a = ["abc_1", "def_1", "pqr_1", "xyz_1"]
z = ["abc_1", "xyz_1"]

a.grep(Regexp.union(z))
# => ["abc_1", "xyz_1"]

Your first example seems to work because #{z} is interpolated as the following expression:

/["abc", "xyz"]/

That is a chararcters class that matches only against "abc" and "xyz". In the second example #{z} is iterpolated as the following characters class:

/["abc_1", "xyz_1"]/

That matches all the strings in the array since they all include the character 1.

Sign up to request clarification or add additional context in comments.

2 Comments

I got my code snippet to work, but I didn't understand the explanation. Can you please elaborate or give me a reference or link. Thanks
I've added a link to the description of character classes, hope it helps.
3

Try this:

a.grep(/#{z.join('|')}/)
# => ["abc_1", "xyz_1"]

It creates valid regexp - with regexp "or" statement - /abc_1|xyz_1/

Comments

2

Both the answers above are perfectly fine as per your question.

but if you are working with arrays why not use & operator

a = ["abc_1", "def_1", "pqr_1", "xyz_1"]
z = ["abc_1", "xyz_1"]
a & z
=> ["abc_1", "xyz_1"]

same answer as using grep and simpler

1 Comment

Sorry, forgot to mention. I want to get a subset of an array with a specific prefix. In that case your method wont work.

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.