Helper to create multi-dimensional arrays

A

adi

Anthony said:
I came up with this method really quick to create x*y arrays in Ruby. It
mimicksArray#new's behavior pretty closely wrt blocks, I hope. What do you all
think?

What about making it more general than just x*y arrays?

class <<Array
def multi(n, *args, &block)
if args.empty?
Array.new(n, &block)
else
Array.new(n) do
Array.multi(*args, &block)
end
end
end
end

?>Array.multi(2){ 0 }
=> [0, 0]
Array.multi(2,2){ 0 } => [[0, 0], [0, 0]]
Array.multi(2,2,2){ 0 } => [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
Array.multi(2,2,2,2){ 0 }

hehe, playing around is fun

Daniel

This is great. Finally a sensible way to create multi-dimensional
arrays in Ruby. Thank you Anthony and Daniel.

Aditya
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top