我有一个字符串和一个数组,并试图遍历该数组以查看其任何元素是否与字符串的一部分匹配。
string = "HOPJYJKCONNECTICUTQZIDAHOKR"
states_array = ["TEXAS", "ALASKA", "IDAHO", "FLORIDA", "MONTANA", "OHIO", "NEWMEXICO", "CONNECTICUT", "COLORADO"]
如何遍历states_数组,以便在字符串中找到所有匹配项我希望将所有匹配的状态输出为一个数组,因此最终结果可能如下所示:
#=> ["CONNECTICUT", "IDAHO"]
最佳答案
string = "HOPJYJKCONNECTICUTQZIDAHOKR"
states = ["TEXAS", "ALASKA", "IDAHO", "FLORIDA", "MONTANA", "OHIO", "NEWMEXICO", "CONNECTICUT", "COLORADO"]
states.select { |s| string[s] }
# => ["IDAHO", "CONNECTICUT"]
关于ruby - 在Ruby中将字符串的部分与数组的元素匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20691076/