Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the first increasing values from Ruby array without enumerating every value?

Tags:

arrays

ruby

Imagine one has an array such as:

a = [0, 1, 2, 3, 4, 2, 5, 1, 7, 6, 4, 5]

And one wishes to create an array consisting of the first n elements, starting with the first element in the array, that are a monotonic sequence increasing by one. Given a above, that array would be [0, 1, 2, 3, 4].

One could use slice_when, such as:

a.slice_when { |a, b| a != b - 1 }.first

The drawback of this approach is that slice_when continues to iterate over the array elements 2, 5, 1, and so on, until the end. In this case, iterating over the remaining values is useless, since one really just wants the first slice.

What is the elegant way to express this in Ruby, that ceases iterating once the first increasing sequence is selected?

like image 350
ybakos Avatar asked May 21 '26 08:05

ybakos


1 Answers

How about lazy evaluation?

a = [0, 1, 2, 3, 4, 2, 5, 1, 7, 6, 4, 5]
a.lazy.slice_when { |a, b| a != b - 1 }.first
 => [0, 1, 2, 3, 4] 

Enumerable#lazy

like image 52
seph Avatar answered May 23 '26 23:05

seph