Enumerable has a really handy method called each_cons , which works like this:
[1,2,3,4].each_cons(2).to_a # => [ [1, 2], [2, 3], [3, 4] ]
That is, it gives each consecutive set of n elements. In our case, n is 2.
Of course, as the name implies, it returns an Enumerator, so can we associate it with other Enumerable methods such as all? :
def four_consecutive?(arr) return false unless arr.size == 4 arr.each_cons(2).all? {|a, b| b == a + 1 } end four_consecutive?([2,3,4,5])
This method has an advantage over others, because since all? closes the chain, as soon as the block returns false, it will only check numbers until it finds a pair that does not meet the condition ( b == a + 1 ). Of course, with just four elements, that doesn't really matter - unless you call this method thousands of times in a situation where performance matters.
source share