For example, if I had an array like:
arr = ["HI","BYE","BYE","BYE"]
Is there a method that would let me know that there are consecutive "BYE"'s in the array?
You can use Enumerable#each_cons for that:
arr = ["HI", "BYE", "BYE", "BYE"]
arr.each_cons(2).any? { |s,t| s == "BYE" && t == "BYE" }
#=> true
arr.each_cons(2).any? { |s,t| s == "HI" && t == "HI" }
#=> false
To determine if any consecutive elements are the same:
arr.each_cons(2).any? { |s,t| s == t }
#=> true
Note that:
enum = arr.each_cons(2)
#=> #<Enumerator: ["HI", "BYE", "BYE", "BYE"]:each_cons(2)>
The elements of this enumerator can be obtained by converting it to an array:
enum.to_a
#=> [["HI", "BYE"], ["BYE", "BYE"], ["BYE", "BYE"]]
The three elements of enum
are passed to the block in turn and assigned to the block variables:
s, t = enum.next
#=> ["HI", "BYE"]
s #=> "HI"
t #=> "BYE"
s, t = enum.next
#=> ["BYE", "BYE"]
s, t = enum.next
#=> ["BYE", "BYE"]
Here are a few other ways of doing this:
Use Enumerable#slice_when (Ruby v2.2+):
arr.slice_when { |a,b| a != b }.any? { |a| a.size > 1 }
#=> true
or Enumerable#chunk (Ruby v1.9.3+) and Object#itself (Ruby v.2.2+).
arr.chunk(&:itself).any? { |_,a| a.size > 1 }
#=> true
or simply step through the array:
arr.any? && (1..arr.size-1).any? { |i| arr[i] == arr[i-1] }
#=> true
arr.any?
is included in case arr
is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With