How can I tell if my string contains a substring from an array?
I thought include?
was the key, but apparently not ...
arr = ["aa", "bb", "cc"]
str = "mystringcc"
str.include?(*arr)
ArgumentError: wrong number of arguments (given 3, expected 1)
In the above example, I would expect the result to be true
since the string has "cc"
, which is an element of the array.
Given:
EDIT: As the other comments have pointed out, this is actually the fastest way, as it breaks the evaluation when a single true statement is found:
The foldl way: I have used this example to illustrate the power of folding expresions. This solution might be somewhat elegant as an illustrative example for foldings, but it is not sufficiently performant.
The
map
-function maps all possible substrings the original stringstr
can have.inject
iterates over the returning array and compares its constituents, using a logical or. If any substring in the array 'arr' is encountered, the result will yield true in the result of map. With the or-relation we return a true value, if any value of the result of map was true. This is slower thanany?
, because every single value in the array gets evaluated even if atrue
is encountered (wich would always yield atrue
at the end ofinject
).