如何知道数组中是否有相同的连续元素?

时间:2022-06-20 21:28:27

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?

有没有一种方法可以让我知道数组中有连续的“BYE”?

1 个解决方案

#1


8  

You can use Enumerable#each_cons for that:

你可以使用可列举的#each_cons:

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:

enum的三个元素依次传递给块,并分配给块变量:

s, t = enum.next
  #=> ["HI", "BYE"] 
s #=> "HI"
t #=> "BYE"

s, t = enum.next
  #=> ["BYE", "BYE"] 

s, t = enum.next
  #=> ["BYE", "BYE"] 

Edit: Here are a couple of other ways of doing this:

编辑:这里有一些其他的方法:

Use Enumerable#slice_when (Ruby v2.2+):

使用可列举的# 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+).

或者是可枚举的#chunk (Ruby v1.9.3+)和对象#本身(Ruby v2.2 +)。

arr.chunk(&:itself).any? { |_,a| a.size > 1 }
  #=> true 

#1


8  

You can use Enumerable#each_cons for that:

你可以使用可列举的#each_cons:

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:

enum的三个元素依次传递给块,并分配给块变量:

s, t = enum.next
  #=> ["HI", "BYE"] 
s #=> "HI"
t #=> "BYE"

s, t = enum.next
  #=> ["BYE", "BYE"] 

s, t = enum.next
  #=> ["BYE", "BYE"] 

Edit: Here are a couple of other ways of doing this:

编辑:这里有一些其他的方法:

Use Enumerable#slice_when (Ruby v2.2+):

使用可列举的# 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+).

或者是可枚举的#chunk (Ruby v1.9.3+)和对象#本身(Ruby v2.2 +)。

arr.chunk(&:itself).any? { |_,a| a.size > 1 }
  #=> true