Hi, welcome to Word of Mike, my little corner of the internet. I am a Software/Web Developer working in North Yorkshire. I mainly write about programming but my other passion is politics so beware. (click to hide)

2013-09-12 20:01:54 UTC

Ruby Multi Dimensional Array Thing


A question was asked in #ruby about making multi dimensional arrays from a single dimensional array, the obvious choice was Enumerable#each_slice, something like:

[1,2,3,4].each_slice(2).to_a
=> [[1, 2], [3, 4]]

Tidy. If we want extra dimensions we have to chain each_slice together over and over, or monkey patch (or refine) like so:

class Array
  def multi_dim(*args)
    args.reduce(self){|a,n| a.each_slice(n)}.to_a
  end
end

array = (1..16).to_a
array.multi_dim(4,2)
=> [[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]]

Woo..