2

I have an array made up of several strings that I am searching for in another array, like so:

strings_array = ["string1", "string2", "string3"]
main_array = [ ## this is populated with string values outside of my script ## ]

main_array.each { |item|
  if strings_array.any? { |x| main_array.include?(x) }
    main_array.delete(item)
  end
}

This is a simplified version of what my script is actually doing, but that's the gist. It works as is, but I'm wondering how I can make it so that the strings_array can include strings made out of regex. So let's say I have a string in the main_array called "string-4385", and I want to delete any string that is composed of string- + a series of integers (without manually adding in the numerical suffix). I tried this:

strings_array = ["string1", "string2", "string3", /string-\d+/.to_s]

This doesn't work, but that's the logic I'm aiming for. Basically, is there a way to include a string with regex like this within an array? Or is there perhaps a better way than this .any? and include? combo that does the job (without needing to type out the complete string value)?

Thank you for any help!

2
  • You could treat every item in your string_array as a regex and instead of main_array.include?(x) you could check whether main_array[x], x being a regex, returns nil, in which case there is no match. Commented Sep 26, 2017 at 20:54
  • You don't need "(ruby)" in the title since you have a Ruby tag. Commented Sep 27, 2017 at 3:04

2 Answers 2

3

You can use methods like keep_if and delete_if, so if you want to delete strings that match a regex you could do something like this:

array = ['string-123', 'test']
array.delete_if{|n| n[/string-\d+/] }

That will delete the strings in the array that do not match your regex. Same thing with keep_if method.

Hope it helps!

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

Comments

1

A good way to do this is with Regexp.union, which combines multiple regular expressions into a single regex handy for matching.

patterns = [/pattern1/, /pattern2/, /string-\d+/]
regex = Regexp.union(patterns)
main_array.delete_if{|string| string.match(regex)}

1 Comment

"Regexp.union" is perfect! It incorporates into the rest of my script exactly as needed. Thank you so much!

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.