user7055375
user7055375

Reputation:

How do I select only the first elements that match?

I'm using Ruby 2.4. I want to select the first consecutive matching elemetns in an array, but then when I encounter an element that doesn't match, I want to stop selecting. So if I want to find strings with a bunch of "a"'s, I could write this

2.4.0 :008 > arr = ["aaaa", "aaaaaaaa", "12345", "aaa"]
 => ["aaaa", "aaaaaaaa", "12345", "aaa"]
...
2.4.0 :010 > arr.select{|string| string.count('a') >= 3 }
 => ["aaaa", "aaaaaaaa", "aaa"]

but under my rules, I don't want to select the last "aaa" element because there was a non-matching element before it. How do I modify what I have so that I only select the first matching elements? Note that if my array were

["1111", "aaaaaa"]

I would want nothing returned since teh very first element in the array doesn't match my conditions.

Upvotes: 0

Views: 48

Answers (1)

Alejandro C.
Alejandro C.

Reputation: 3801

#take_while does what you want: https://ruby-doc.org/core-2.4.1/Enumerable.html#method-i-take_while

arr.take_while { |s| s.count('a') >= 3 }
=> ["aaaa", "aaaaaaaa"]

Upvotes: 4

Related Questions