How do I find the first two consecutive elements in my array of numbers?

前端 未结 5 826
长发绾君心
长发绾君心 2021-01-25 06:06

Using Ruby 2.4, I have an array of unique, ordered numbers, for example

[1, 7, 8, 12, 14, 15]

How do I find the first two elements whose differ

5条回答
  •  耶瑟儿~
    2021-01-25 06:51

    You could use each_cons and find to get the first element from the array of pairs where the second element less the first one is equal to 1:

    p [1, 7, 8, 12, 14, 15].each_cons(2).find { |a, b| b - a == 1 }
    # => [7, 8]
    

提交回复
热议问题