Slicing arrays based on relations in the data (in Ruby) -


i have arrays in form: [1, 2, 1, 4, 5, 4, 1, 7, 7, 6] , need slice them [[1, 2, 1], [4, 5, 4], [1], [7, 7, 6]], breaks determined absolute difference between consecutive pairs being larger 1.

is there in ruby magic can harness, or left having code plain old iteration?

you can use enumerable#slice_when:

a = [1, 2, 1, 4, 5, 4, 1, 7, 7, 6] a.slice_when { |i, j| (i - j).abs > 1 }.to_a #=> [[1, 2, 1], [4, 5, 4], [1], [7, 7, 6]] 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -