Hi,

I need a 3-dim array. The following attempt shows some unexpected
results:

irb(main):001:0> a = Array.new(3)
=> [nil, nil, nil]
irb(main):002:0> a.map!{Array.new(3,[])}
=> [[[], [], []], [[], [], []], [[], [], []]]
irb(main):003:0> a[1][1] << 3.0
=> [3.0]
irb(main):004:0> a
=> [[[], [], []], [[3.0], [3.0], [3.0]], [[], [], []]]

(my expectation would be:
[[[], [], []], [[], [3.0], []], [[], [], []]]
)


After some searching in the forum I found another method:
irb(main):007:0* b = Array.new(3) {Array.new(3,[])}
=> [[[], [], []], [[], [], []], [[], [], []]]
irb(main):008:0> b[1][1] << 3.0
=> [3.0]
irb(main):009:0> b
=> [[[], [], []], [[3.0], [3.0], [3.0]], [[], [], []]]

again, not the expected behavior.

However:
irb(main):016:0> c = Array.new(3) {Array.new(3) {[]}}
=> [[[], [], []], [[], [], []], [[], [], []]]
irb(main):017:0> c[1][1] << 3.0
=> [3.0]
irb(main):018:0> c
=> [[[], [], []], [[], [3.0], []], [[], [], []]]

gives me what I want.

Could anybody please explain to me why my expectations are wrong in the
first two cases?

Thanks,
Armin
-- 
Posted via http://www.ruby-forum.com/.