Reputation: 39
I have a string & an array, and am trying to iterate through the array to see of any of its elements match a portion of the string.
string = "HOPJYJKCONNECTICUTQZIDAHOKR"
states_array = ["TEXAS", "ALASKA", "IDAHO", "FLORIDA", "MONTANA", "OHIO", "NEWMEXICO", "CONNECTICUT", "COLORADO"]
How can I iterate overs the states_array so that I can find all matches in the string? I would want to output all the matched states as an array & so the final result might look like:
#=> ["CONNECTICUT", "IDAHO"]
Upvotes: 1
Views: 134
Reputation: 80065
This is like @Peter_Alvin's answer,using the built in method union
.
states_array = ["TEXAS", "ALASKA", "IDAHO", "FLORIDA", "MONTANA", "OHIO", "NEWMEXICO", "CONNECTICUT", "COLORADO"]
str = "HOPJYJKCONNECTICUTQZIDAHOKR"
p str.scan(Regexp.union(states_array)) # ["CONNECTICUT", "IDAHO"]
Upvotes: 0
Reputation: 29399
Since you specified the regex tag on this question, you could do with with a regex as follows:
string.scan(Regexp.new(states.join('|')))
# => ["CONNECTICUT", "IDAHO"]
using the variables in Matt's answer. Not recommending this, however. :-)
Upvotes: 1
Reputation: 2865
Nice solution by Matt but can also be done
states.select { |s| string.match(s)}
Upvotes: 2
Reputation: 20786
string = "HOPJYJKCONNECTICUTQZIDAHOKR"
states = ["TEXAS", "ALASKA", "IDAHO", "FLORIDA", "MONTANA", "OHIO", "NEWMEXICO", "CONNECTICUT", "COLORADO"]
states.select { |s| string[s] }
# => ["IDAHO", "CONNECTICUT"]
Upvotes: 5