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
Here are three more ways.
#1
def first_adjacent_pair(arr)
(arr.size-2).times { |i| return arr[i, 2] if arr[i+1] == arr[i].next }
nil
end
first_adjacent_pair [1, 7, 8, 12, 14, 15] #=> [7,8]
first_adjacent_pair [1, 7, 5, 12, 14, 16] #=> nil
#2
def first_adjacent_pair(arr)
enum = arr.to_enum # or arr.each
loop do
curr = enum.next
nxt = enum.peek
return [curr, nxt] if nxt == curr.next
end
nil
end
enum.peek
raises a StopIteration
exception when the enumerator enum
has generated its last element with the preceding enum.next
. The exception is handled by Kernel#loop by breaking out of the loop, after which nil
is returned. See also Object#to_enum, Enumerator#next and Enumerator#peek.
#3
def first_adjacent_pair(arr)
a = [nil, arr.first]
arr.each do |n|
a.rotate!
a[1] = n
return a if a[1] == a[0] + 1
end
nil
end
See Array#rotate!.