Reputation: 86097
Given this array:
["/Item A/", "/Item B/"]
and a line:
Here's a line of text that includes /Item B/
what's a good, idiomatic, Ruby way of checking if the line includes at least one phrase from the array?
Upvotes: 1
Views: 61
Reputation: 110675
If elements of the array follow a pattern, as in your example, you may wish to use a regex to improve efficiency. For example:
a = ("A".."X").map { |c| "/Item #{c}/" }
#=> ["/Item A/", "/Item B/", "/Item C/",..., "/Item X/"]
"I considered /Item Y/ and /Item R/. I want the R!" =~ /\/Item [A-X]\// #=> 26
"I considered /Item Y/ and /Item Z/. I want the Z!" =~ /\/Item [A-X]\// #=> nil
Upvotes: 0
Reputation: 4156
Above answer is very nice, You can also try the following code snippet using any?
and include?
a = ["/Item A/", "/Item B/"]
l = "Here's a line of text that includes /Item B/"
a.any? { |e| l.include?(e) }
=> true
Upvotes: 2
Reputation: 19879
Couple of ways. Speed may depend on the size of your array and line. Might want to run some benchmarks to see:
> a = ["/Item A/", "/Item B/"]
> l = "Here's a line of text that includes /Item B/"
Then using any?
:
> a.any?{|e| l.index(e)}
=> true
Or using a Regexp:
> l =~ Regexp.union(a)
=> 36
Upvotes: 4