您的位置:首页 > 编程语言 > Ruby

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

2014-06-21 19:35 621 查看
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"]

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

states.select { |s| string[s] }
# => ["IDAHO", "CONNECTICUT"]
Nice solution by Matt but can also be done
states.select { |s| string.match(s)}
string.scan(Regexp.new(states.join('|')))
# => ["CONNECTICUT", "IDAHO"]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: