Multi-dimension array

Hi Guru,

You’re doing too much work – let Ruby do it :slight_smile:

arr = (1…3).map { [0,0] }

That’s really neat. Thanks for show us the ruby way.

Shannon

···

The new MSN 8: advanced junk mail protection and 2 months FREE*
http://join.msn.com/?page=features/junkmail

Here’s a quick extension to several dimensions, using Joel VanderWerf’s
enum tools ( http://www.ruby-lang.org/raa/list.rhtml?id=657 )

require 'enum/tree’
require ‘enum/op’

class << Array
def n_dim(*args)
return (1…args[0]).to_a.map! {nil} if args.length == 1
a = args.shift
(1…a).to_a.map! {n_dim(*args)}
end
end

class Array
def deep_each
self.by_depth { |x| x.kind_of?(Array) ? x : [] }.each {|i|
yield i unless i.kind_of?(Array)
}
end
end

include EnumerableOperator
a = Array.n_dim(2,3,4)

product(0…1, 0…2, 0…3).each {|i,j,k| a[i][j][k] = “(#{i},#{j},#{k})” }

a.deep_each {|i| p i}

···

Shannon Fang xrfang@hotmail.com wrote:

Hi Guru,

You’re doing too much work – let Ruby do it :slight_smile:

arr = (1…3).map { [0,0] }

That’s really neat. Thanks for show us the ruby way.

Hi –

require 'enum/tree’
require ‘enum/op’

class << Array
def n_dim(*args)
return (1…args[0]).to_a.map! {nil} if args.length == 1
a = args.shift
(1…a).to_a.map! {n_dim(*args)}
end
end

class Array
def deep_each
self.by_depth { |x| x.kind_of?(Array) ? x : [] }.each {|i|
yield i unless i.kind_of?(Array)
}
end
end

Couldn’t you achieve the same thing with flatten?

def deep_each
flatten.each {|e| yield e}
end

(I haven’t used the enum tools, so there may be aspects I’m
overlooking.)

David

···

On Mon, 9 Dec 2002, Martin DeMello wrote:


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav

dblack@candle.superlink.net wrote:

Couldn’t you achieve the same thing with flatten?

def deep_each
flatten.each {|e| yield e}
end

LOL - so you could :slight_smile:

(I haven’t used the enum tools, so there may be aspects I’m
overlooking.)

No, that had started off life as Enumerable#deep_each, and then moved
over to Array because it recursed into Strings too. Forgot that Array
already had a perfectly good solution.

martin