Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you know if an array has consecutive elements that are the same?

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?

like image 543
Jorge Lopez Jr Avatar asked Dec 15 '22 12:12

Jorge Lopez Jr


1 Answers

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.

like image 112
Cary Swoveland Avatar answered Feb 12 '23 12:02

Cary Swoveland