Reputation:
I'm using Rails 5 and Ruby 2.4. If I have an array of strings, how do I figure out if there are two consecutive strings that match a regular expression?
For instance, I have:
["1234", "aa", "cc33", "44"]
I want to see if there are two consecutive elements that begin with letters (in the above case, that condition is true
, "aa"
and "cc33"
). But in the below case it would be false
:
["bb", "55", "mm", "77"]
This
my_arr.select { |str| str =~ /^\p{L}/ }
tells me how many strings begin with letters, but it doesn't tell me if I have two consecutive elements that begin with letters.
How do I figure that out?
Upvotes: 1
Views: 305
Reputation: 110675
I understand you wish to determine if two consecutive elements of an array match a given regular expression. To do that efficiently we would like check as few elements (strings) as possible for matches. In particular, we don't want to necessarily check all elements of the array or check individual elements twice. Here is one way to do that.
arr = ["1234", "aa", "cc33", "44"]
r = /\A[[:alpha:]]{2}/
a = [false, false]
arr.any? do |s|
a[0] = s.match?(r)
a.rotate! == [true, true]
end
#=> true
String#match? made its debut in Ruby v2.4. For earlier versions one could write !!(s =~ r)
. The inner exclamation mark convert a truthy value to false
and a falsy value to true
; the outer exclamation mark flips that result from true
to false
and vice-versa.
Upvotes: 0
Reputation: 10497
Using your same regex, you could do this:
my_arr.each_cons(2).any? { |pair| pair.all? { |elem| elem =~ /^\p{L}/ } }
Check this snippet.
Upvotes: 3