BandanaKM
BandanaKM

Reputation: 39

Matching Portions of A String to Elements of an Array in Ruby

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

Answers (4)

steenslag
steenslag

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

Peter Alfvin
Peter Alfvin

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

aarti
aarti

Reputation: 2865

Nice solution by Matt but can also be done

states.select { |s| string.match(s)}

Upvotes: 2

Matt
Matt

Reputation: 20786

string = "HOPJYJKCONNECTICUTQZIDAHOKR"
states = ["TEXAS", "ALASKA", "IDAHO", "FLORIDA", "MONTANA", "OHIO", "NEWMEXICO", "CONNECTICUT", "COLORADO"]

states.select { |s| string[s] }
# => ["IDAHO", "CONNECTICUT"]

Upvotes: 5

Related Questions