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"]
相关文章推荐
- How to find number of a specific integer in an array of Fixnums ruby
- Whats the best way to split an array in ruby into multiple smaller arrays of random size
- how to remove nil and blank string in an array in Ruby
- Converting a array to an array of ranges in ruby
- Ruby: Count unique elements and their occurences in an array
- Get indices for sorted permutation of an array in Ruby?
- How to get array from string contained identical symbols in Ruby?
- Condensing an array of hashes within that same array in Ruby
- (NOT CLEAR)Question 40: In the declaration below, p is a pointer to an array of 5 int pointers:
- Generating a string with elements from an array based on pattern matching
- The minimum number of elements to reach the end of an array
- How to format strings in an array in ruby?
- Find the two non-repeating elements in an array of repeating elements
- Ruby remove substring matching to any element of array
- Sorting an array of hash in Ruby
- How to get array from string contained identical symbols in Ruby?
- how to merge array of hash based same keys in ruby?
- Ruby: Sorting an array of strings, in alphabetical order, that includes some arrays of strings
- Err:The "." operator was supplied with an index value of type "java.lang.String" to be applied to a List or array
- Given an array of integers, sort the array according to frequency of elements