erli
erli

Reputation: 408

Check if string contains substring in array AND get the match

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?

Upvotes: 1

Views: 543

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

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.

Upvotes: 5

Ursus
Ursus

Reputation: 30071

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

Upvotes: 2

Related Questions