2

I have two arrays:

a = ["X2", "X3/X4", "X5/X6/X7", "X8/X9/X10/X11"]
b = ["X9/X10", "X3/X4"]

Now I need to select entries from 'a' array which regexp with any of entries from array 'b'.

Expected result is:

["X3/X4", "X8/X9/X10/X11"]

How can I do this in Ruby?

4 Answers 4

4

I'd do:

a.grep(Regexp.union(b))
# => ["X3/X4", "X8/X9/X10/X11"] 
Sign up to request clarification or add additional context in comments.

2 Comments

TypeError: can't convert Array into String from (irb):281:in `union'
@user2562153 What Ruby version are you using?
2

This should work:

a.grep(/#{b.join('|')}/)
# => ["X3/X4", "X8/X9/X10/X11"]

Comments

2

Try the below:

 a = ["X2", "X3/X4", "X5/X6/X7", "X8/X9/X10/X11"] 
 b = ["X9/X10", "X3/X4"]
 p a.select{|i| b.any?{|j| i.include? j }}
 #>> ["X3/X4", "X8/X9/X10/X11"]

Comments

0

The safest way is to build a regular expression and then select elements of your array matching this expression:

Regexp.union("a", "b", "c")
# => /a|b|c/

Regexp.union(["a", "b", "c"])
# => /a|b|c/

("b".."e").to_a.grep(Regexp.union("a", "b", "c"))
# => ["b", "c"]

1 Comment

Code-only answers do very little to educate SO readers. Your answer may or may not be a correct answer, but it is in the moderation queue after being marked as "low-quality". Please take a moment to improve your answer with an explanation.

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.