Ruby Built In Method to Create Multidimensional Array From Single Dimensioned Array
- by Ell
If I have an array like this: [0, 1, 2, 3, 4, 5], is there a built in method to create this:
[[0, 1, 2], [3, 4, 5]] given a width of 3? If there is no built in method, how could I improve on this?
def multi_to_single(array, width)
return [].tap{|md_array|
(array.length.to_f / width).ceil.times {|y|
row = (array[(y*width), width])
md_array.push( row + Array.new(width - row.length))
}
}
end
I feel like I have missed something obvious because I haven't programmed ruby in a while!
Thanks in advance, ell.
EDIT: It needs to be in the core library, so no ruby on rails or anything.