Ruby Built In Method to Create Multidimensional Array From Single Dimensioned Array
Posted
by
Ell
on Stack Overflow
See other posts from Stack Overflow
or by Ell
Published on 2012-01-15T12:15:52Z
Indexed on
2012/06/11
22:40 UTC
Read the original article
Hit count: 294
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.
© Stack Overflow or respective owner