1

I've seen a couple threads here that shows the most efficient way to check a string against an array of substrings and return a boolean if there is a match.

str = "foobazbar"
arr = ["baz", "clowns"]
result = arr.any? { |substring| str.include?(substring) } # solution
result => true

However, as elegant and efficient as that solution is, is there any way to return the match itself? Using the example from above, I also want to know that the match was baz. What is the best way to accomplish this?

3
  • Umm, your code example doesn't match your result. "foobazbar" does not contain the substring "baz, clowns", so result should be false. Commented Sep 28, 2019 at 17:48
  • If "baz" and "clowns" are the substrings you are looking for, you will first have to parse the contents of the array. Commented Sep 28, 2019 at 17:49
  • @JörgWMittag Woops, made a typo in the arr line. Fixed it. Seems like the solution posted by @Ursus works Commented Sep 28, 2019 at 17:56

2 Answers 2

5
str = "foobazbar"
arr = ["baz", "clowns", "bar"]

r = Regexp.union(arr) #=> /baz|clowns|bar/ 

str[r]                #=> "baz"
str.scan(r)           #=> ["baz", "bar"] 

See Regexp::union, String#[] and String#scan.

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

Comments

2
str = "foobazbar"
arr = ["baz", "clowns"]
result = arr.find { |s| str.include?(s) }

result at this point is the first element in arr that is a substring of str or is nil

2 Comments

Follow up question: What would be a good way to get an array of all matches rather than just the first element that matches? arr = ["foo","clowns", "baz"] result => ["foo","baz"]
@erli: Replace find by select.

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.