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

timeout - Handshake_timeout on RabbitMQ using python and pika from remote vm -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

c# - Search and Add Comment with OpenXML for Word -