Whats the best way to split an array in ruby into multiple smaller arrays of random size

来源:互联网 发布:tcl人工智能电视 编辑:程序博客网 时间:2024/04/29 17:28

I have multiple arrays in ruby of variable length from 1 to 40 :

@items is a typical array which could be anywhere from 1 to 40 in length. eg

@items = [1, 2, 3, 4, 5, 6]

I want to randomly split the array into smaller arrays of lengths either 1, 2 or 3 to give a result of (for example)

@items = [[1, 2],[3],[4,5,6]]

or

@items = [[1],[2, 3],[4],[5,6]]

etc

items, @items = @items.dup, []@items.push(items.shift(rand(1..3))) until items.empty?

0 0