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

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -