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

arrays, random, ruby, slice

Solution

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

Problem

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 I know you can split the array using @items.each_slice(3)... where 3 is a fixed length. But i want to randomly split large arrays of variable length into array sizes of 1,2 or 3 randomly... Whats the best way to achieve this?

Original source